How to Process Collatz Conjecture Test in Python


Here let us see how to process the Collatz conjecture test for a given number in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

n = int(input("Please input a number: "))
print("The sequence is: ", end=" ")
while n > 1:
    print(n, end=" ")
    if n % 2 == 0:
        n = n // 2
    elif n % 2 == 1:
        n = n * 3 + 1
print(n, end=" ")

Output:

Please input a number: 8
The sequence is:  8 4 2 1

Please input a number: 7
The sequence is:  7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments