Skip to content

Commit 48e31ce

Browse files
committed
step-by-step Collatz sequence
1 parent d65cbc6 commit 48e31ce

File tree

1 file changed

+18
-24
lines changed

1 file changed

+18
-24
lines changed

Collatz Sequence/Collatz Sequence.py

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,23 @@
1-
def collatz_steps(n):
2-
times = 0
1+
def collatz_sequence(n):
2+
"""Generate and print the Collatz sequence for n."""
3+
steps = [n]
34
while n != 1:
45
if n % 2 == 0:
5-
print(f"{n} / 2", end=" ")
6-
n = n // 2 # "//" is a floor division where it rounds down the result
6+
n = n // 2
77
else:
8-
print(f"{n} * 3 + 1", end=" ")
98
n = 3 * n + 1
10-
print(f"= {n}")
11-
times += 1
12-
print(f"The number of times to reach 1 is {times}")
9+
steps.append(n)
10+
return steps
1311

14-
def main():
15-
again = "y"
16-
while again != "n":
17-
n = int(input("Input a number: "))
18-
collatz_steps(n)
19-
while True:
20-
again = str(input("Want to input again? y/n: "))
21-
if again != "n" and again != "y":
22-
print("Incorrect Input.")
23-
elif again == "n":
24-
print("Thank You! Goodbye.")
25-
break
26-
else:
27-
break
28-
29-
main()
12+
# --- Main Program ---
13+
try:
14+
num = int(input("Enter a positive integer: "))
15+
if num <= 0:
16+
print("Please enter a positive number greater than 0.")
17+
else:
18+
sequence = collatz_sequence(num)
19+
print("\nCollatz sequence:")
20+
for i, value in enumerate(sequence, start=1):
21+
print(f"Step {i}: {value}")
22+
except ValueError:
23+
print("Invalid input! Please enter an integer.")

0 commit comments

Comments
 (0)