forked from Twiggecode/Integer-Sequences
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollatz_Conjecture.py
57 lines (42 loc) · 1.23 KB
/
Collatz_Conjecture.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Python3 program to implement Collatz Conjecture
# Function to find if n reaches to 1 or not.
# O(n) solution
def isToOneRec(n: int, s: set) -> bool:
if n == 1:
return True
# If there is a cycle formed,
# we can't reach 1.
if n in s:
return False
# If n is odd then pass n = 3n+1 else n = n/2
if n % 2:
return isToOneRec(3 * n + 1, s)
else:
return isToOneRec(n // 2, s)
# Wrapper over isToOneRec()
def isToOne(n: int) -> bool:
# To store numbers visited
# using recursive calls.
s = set()
return isToOneRec(n, s)
# Driver Code
if __name__ == "__main__":
n = int(input())
if isToOne(n):
print("Yes, the number reaches to one after the above operations ")
else:
print("No, it does not reach one ")
# We can also make use of the Collatz conjecture which states that every positive number
#can reach to one after the following operations (in the commnets above)
# O(1) solution
# Uncomment below code to see the O(1) solution
#def isToOne(n):
# # Return true if n
# # is positive
# return (n > 0)
# # Drivers code
# n = int(input())
# if isToOne(n) == True:
# print("Yes")
# else:
# print("No")