turner-townsend-backend-ass.../collatz/collatz.py

36 lines
901 B
Python
Raw Normal View History

import readline
2025-08-31 11:34:20 +01:00
class CollatzCalculator:
def calculate_steps(self, n: int) -> int:
if n <= 1:
return 0
steps = 0
while n != 1:
if n % 2 == 0:
n //= 2
print(f"Step #{steps + 1}: even, divide by 2 -> {n}")
else:
n = 3 * n + 1
print(f"Step #{steps + 1}: odd, multiply by 3 and add 1 -> {n}")
steps += 1
return steps + 1
2025-08-31 11:34:20 +01:00
def main():
calculator = CollatzCalculator()
while True:
try:
n = input("Please enter a whole number: ")
2025-08-31 11:34:20 +01:00
print(
f"Result: {calculator.calculate_steps(int(n))} steps needed to reach {n}"
)
except ValueError:
print("ERROR: integer required")
except (EOFError, KeyboardInterrupt):
break
2025-08-31 11:34:20 +01:00
if __name__ == "__main__":
main()