How to calculate the Collatz sequence for a range starting from 3 to 10 in Python

1 Answer

0 votes
def CalcCollatz(x) :
    if (x % 2 == 0) : # even
        x = x // 2
    else : # odd
        x = (3 * x) + 1
    
    return x;

def PrintCollatzSequence(x) :
    lst = list()
    lst.append(x) 
    
    while (x != 1) :
        x = CalcCollatz(x)
        lst.append(x) 
   
    print(' '. join(str(i) for i in lst))  


i = 3
while (i < 11) :
    PrintCollatzSequence(i)
    i += 1



'''
run:

3 10 5 16 8 4 2 1
4 2 1
5 16 8 4 2 1
6 3 10 5 16 8 4 2 1
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
8 4 2 1
9 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
10 5 16 8 4 2 1

'''

 



answered Nov 7, 2023 by avibootz
...