W WolfCode · CSC 141

Homework: Collatz Steps

作业: Collatz 步数

≈ 30 min · python-loops python-conditionals · Open in WolfCode

The textbook's own §7.3 example as a graded problem. The math is unsolved; the program is straightforward.

The rule

Start with a positive integer n. Each step:

  • If n is even → n = n // 2
  • If n is odd → n = 3 * n + 1

Stop when n == 1. Count steps.

Worked trace — n = 3

Python · runnable

The integer-vs-float trap

Why // matters

Why n = 27 is famous

The sequence takes 111 steps and reaches a peak of 9232 before coming down. Yet 27 isn't special — the sequence is just chaotic. From Think Python §7.3: "So far, no one has been able to prove [it terminates for all positive n] or disprove it."

Acceptance criteria

  • All 7 tests pass
  • Uses a while loop (not recursion)
  • Uses // for the even step (not /)
  • Returns an int