31 lines
868 B
Python
31 lines
868 B
Python
|
|
import readline
|
||
|
|
|
||
|
|
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
|
||
|
|
|
||
|
|
def main():
|
||
|
|
calculator = CollatzCalculator()
|
||
|
|
while True:
|
||
|
|
try:
|
||
|
|
n = input("Please enter a whole number: ")
|
||
|
|
print(f"Result: {calculator.calculate_steps(int(n))} steps needed to reach {n}")
|
||
|
|
except ValueError:
|
||
|
|
print("ERROR: integer required")
|
||
|
|
except (EOFError, KeyboardInterrupt):
|
||
|
|
break
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
main()
|