Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 18 additions & 24 deletions Collatz Sequence/Collatz Sequence.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,23 @@
def collatz_steps(n):
times = 0
def collatz_sequence(n):
"""Generate and print the Collatz sequence for n."""
steps = [n]
while n != 1:
if n % 2 == 0:
print(f"{n} / 2", end=" ")
n = n // 2 # "//" is a floor division where it rounds down the result
n = n // 2
else:
print(f"{n} * 3 + 1", end=" ")
n = 3 * n + 1
print(f"= {n}")
times += 1
print(f"The number of times to reach 1 is {times}")
steps.append(n)
return steps

def main():
again = "y"
while again != "n":
n = int(input("Input a number: "))
collatz_steps(n)
while True:
again = str(input("Want to input again? y/n: "))
if again != "n" and again != "y":
print("Incorrect Input.")
elif again == "n":
print("Thank You! Goodbye.")
break
else:
break

main()
# --- Main Program ---
try:
num = int(input("Enter a positive integer: "))
if num <= 0:
print("Please enter a positive number greater than 0.")
else:
sequence = collatz_sequence(num)
print("\nCollatz sequence:")
for i, value in enumerate(sequence, start=1):
print(f"Step {i}: {value}")
except ValueError:
print("Invalid input! Please enter an integer.")