354
pages

By: Tao Steven Zheng (郑涛)

A Hailstone sequence is generated from a starting positive integer  by the following program:

•   If  is 1 then the sequence ends.
•   If  is even then the next number of the sequence
•   If  is odd then the next number of the sequence

The unproven Collatz conjecture states that the hailstone sequence for any starting positive integer always terminates (by reaching 1). This sequence was named by Lothar Collatz (1910 - 1990) in 1937.

Create a function to generate the hailstone sequence for any integer number (make sure to exclude non-positive integers).

Code

``` 1 def hailstone(n):
2     sequence = [n]
3     if n < 1:
4         print("Cannot generate sequence. Not a positive integer!")
5     if n == 1:
6         print([1])
7     if n > 1:
8         while n > 1:
9             if n % 2 == 1:
10                 n = 3 * n + 1
11                 sequence.append(n)
12             if n % 2 == 0:
13                 n = n // 2
14                 sequence.append(n)
15         return sequence
16 #        print(sequence)
17 #        print(len(sequence))
18
19 '''Experiments'''
20 hailstone(-10)
21 hailstone(1)
22 print(hailstone(10))
23 print(len(hailstone(10)))
24 print(hailstone(9))
25 print(len(hailstone(9)))
```