The Collatz sequence is generated based on the following conditions:
n//2
.3*number+1
.We then continue this process until the function returns the value of 1
.
Check wether or not the number is equal to one.
Check if a number is even or odd. If the number is even, print number//2
; if the number is odd, print 3 * number+1
.
Let the number be 11:
11 is odd, return 3*11+1=34
34 is even, return 34//2 = 17
17 is odd, return 17*3+1=52
52 is even, return 52//2=26
26 is even, return 26//2=13
13 is odd, return 13*3+1=40
40 is even,return 40//2=20
20 is even, return 20//2=10
10 is even, return 10//2=5
5 is odd, return 5*3+1=16
16 is even, return 16//2=8
8 is even, return 8//2=4
4 is even, return 4//2=2
2 is even,return 2//2=1
def collatz(number): lst=[] lst.append(number) while(number!=1): if(number%2==0): number=number//2 lst.append(number) else: number=number*3+1 lst.append(number) print(lst) collatz(11)
An empty list is taken to store all sequence values.
While
loop is taken to check if the condition is equal to one.
If the number is not equal to one, the number is checked to see if it is even
or odd
. Based on this result, the subsequent operation is performed.
All the values are appended to the list.
The list is the Collatz sequence of the given number.
RELATED TAGS
CONTRIBUTOR
View all Courses