1 If a number is even then the next number is that number di
1.
If a number is even, then the next number is that number divided by 2. Eg. 10->5
If a number is odd, then the next number is 3 times the number plus 1. Eg 5->16
Your function should stop when the sequence gets to 1. Note that it is an open question whether the Collatz sequence for every positive integer always ends at 1. Sample usage:
>>> collatz(10)
[10, 5, 16, 8, 4, 2, 1]
>>> collatz(22)
[22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
Solution
Code:
def collatz(n):
l = [] #declaring an empty list
l.append(n) #adding the passed value to the list
while (n != 1): #iterating the loop until we get n value as 1
if(n%2 == 0): # checking if n is even
n = n/2 # if n is even dividing that with 2
l.append(int(n))# adding that new value of n to the list
elif(n%2 == 1): # checking if n is odd
n = n*3+1 # if n is odd multiplying n with 3 and adding 1
l.append(int(n)) # adding that new value of n to the list
else:
None
return l #returning the list
print(collatz(10)) #calling the funciton for different values of n
print(collatz(22))
print(collatz(50))
Output:
