-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollatzProblem.py
More file actions
35 lines (30 loc) · 932 Bytes
/
CollatzProblem.py
File metadata and controls
35 lines (30 loc) · 932 Bytes
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
"""
Author: Junwei Luo
Collatz probelm: any positive integer, if is even, then divide by two; if odd, times 3 plus 1.
Continue doing last step, eventually any positive integer will get to 1.
"""
# define function for collatz
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return 3 * number + 1
# ask for an positive input; if not a positive input, ask again.
while True:
input1 = input("Please input an positive integer: ")
try:
intInput = int(input1)
if intInput > 0:
break
else:
print("Not an positive integer. Please input again: ")
except:
print("Not an integer. Please input again: ")
# print result of collatz transformation and collatz again until 1.
while True:
print(intInput)
if collatz(intInput) == 1:
print(collatz(intInput))
break
else:
intInput = collatz(intInput)