Hailstone Sequence in Python using Recursion

Write a recursive/iterative function which takes a number N as function argument and displays the Hailstone Sequence of that number. The sequence should stop when the sequence reaches 1.

Definition: The Hailstone Sequence of numbers can be generated from a starting positive integer, N by:
a) If N = 1 then the sequence ends.
b) If N is Even, then the next N of the sequence = n / 2.
c) If N is Odd, then the next N of the sequence = 3 × n + 1.

The (unproven) Collatz conjecture is that the Hailstone Sequence for any starting number always terminates.

The Hailstone Sequence is also known as Hailstone Numbers because the values are usually subject to multiple descents and ascents like hailstone in a cloud.

This sequence is also known as the Collatz Sequence.

Examples:
INPUT:
N = 7
OUTPUT:
Hailstone Numbers: 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
Number of steps required: 17

INPUT:
N = 9
OUTPUT:
Hailstone Numbers: 9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
Number of steps required: 20

In the first example, N = 7.
The numbers will be calculated as follows:
7
3 × 7 + 1 = 22 (since 7 is odd)
22 / 2 = 11 (since 22 is even)
3 × 11 + 1 = 34 (since 11 is odd)

and so on up to 1.

def collatz(num, steps = 0):
    if num == 1:
        steps = steps + 1
        print(num)
        print("Number of steps required: " + str(steps))
    elif num % 2 == 0:
        print(num, end = ", ")
        collatz(num // 2, steps + 1)
    else:
        print(num, end = ", ")
        collatz(3 * num + 1, steps + 1)

num = abs(int(input("Enter the number: ")))
print("Hailstone Numbers:", end = " ")
collatz(num)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.