斯坦福大学开放课程——编程方法 作业2 - 6

 

6.

     Douglas Hofstadter’s Pulitzer-prize-winning book Gödel, Escher, Bach contains many interesting mathematical puzzles, many of which can be expressed in the form of computer programs. In Chapter XII, Hofstadter mentions a wonderful problem that is well within the scope of the control statements from Chapter 4. The problem can be expressed as follows:

Pick some positive integer and call it n.

If n is even, divide it by two.

If n is odd, multiply it by three and add one.

Continue this process until n is equal to one.

    On page 401 of the Vintage edition, Hofstadter illustrates this process with the following example, starting with the number 15:

15   is odd, so I make 3n+1:   46

46   is even, so I take half:     23

23   is odd, so I make 3n+1:   70

70   is even, so I take half:     35

35   is odd, so I make 3n+1:   106

106 is even, so I take half:     53

53   is odd, so I make 3n+1:   160

160 is even, so I take half:     80

80   is even, so I take half:     40

40   is even, so I take half:     20

20   is even, so I take half:     10

10   is even, so I take half:     5

5     is odd, so I make 3n+1:   16

16   is even, so I take half:     8

8     is even, so I take half:     4

4     is even, so I take half:     2

2     is even, so I take half:     1

 

    As you can see from this example, the numbers go up and down, but eventually—at least for all numbers that have ever been tried—comes down to end in 1. In some respects, this process is reminiscent of the formation of hailstones, which get carried upward by the winds over and over again before they finally descend to the ground. Because of this analogy, this sequence of numbers is usually called the Hailstone sequence, although it goes by many other names as well.

    Write a ConsoleProgram that reads in a number from the user and then displays the Hailstone sequence for that number, just as in Hofstadter’s book, followed by a line showing the number of steps taken to reach 1. For example, your program should be able to produce a sample run that looks like this:

 

 

 

    The fascinating thing about this problem is that no one has yet been able to prove that it always stops. The number of steps in the process can certainly get very large. How many steps, for example, does your program take when n is 27?

 

 

程序源代码:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值