Collatz Conjecture Sequence Generator in Python

Collatz conjecture is one of the unsolved problems in mathematics.

According to wikipedia, Collatz conjecture asks whether repeating two simple arithmetic operations will eventually transform every positive integer into 1. It concerns sequences of integers in which each term is obtained from the previous term as follows: if the previous term is even, the next term is one half of the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1.

Mathematically for any arbitrary positive integer number n, Collatz conjecture sequence is generated by using following mathematical function:

f(n) = n/2        if n is even
      3n + 1     if n is odd

Python Source Code


# Collatz sequence generation
def collatz(n):
    temp = []
    while True:
        n = n // 2 if n % 2 == 0 else 3*n + 1
        temp.append(n)
        
        if n == 1:
            break
    return temp

# driver code
start_num = int(input("Enter starting positive integer number for Collatz sequence: "))
collatz_sequences = collatz(start_num)
print("Collatz sequence for positive integer ", start_num, " is:")
for num in collatz_sequences:
    print(num)

The output of the the above program is:

Enter starting positive integer number for Collatz sequence: 11
Collatz sequence for positive integer  11  is:
34
17
52
26
13
40
20
10
5
16
8
4
2
1

Using Python's Generator Function

Above program can be modified to use Python's generator function as follows:


# Collatz sequence generator function
def collatz(n):
    while True:
        n = n // 2 if n % 2 == 0 else 3*n + 1
        yield n
        
        if n == 1:
            break

# driver code
start_num = int(input("Enter starting positive integer number for Collatz sequence: "))
collatz_sequences = collatz(start_num)

print("Collatz sequence for positive integer ", start_num, " is:")
for num in collatz_sequences:
    print(num)

print("Type of collatz_sequences is: ", type(collatz_sequences))

The aoutput of the above program is:

Enter starting positive integer number for Collatz sequence: 11
Collatz sequence for positive integer  11  is:
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Type of collatz_sequences is:  <class 'generator'>