Read the question, write Python on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
The Collatz rule: if n is even, replace it with n / 2; if odd, replace it with 3n + 1. Repeat until n is 1.
Read a starting n and print how many steps it takes to reach 1. If n is already 1, print 0.
Input. One line: an integer n ≥ 1.
Output. One integer: the step count.
Constraints
- 1 ≤ n ≤ 10,000
Examples
Input
6
Output
8
Input
1
Output
0
Hint
- while n != 1: if n % 2 == 0: n //= 2 else: n = 3 * n + 1; steps += 1
- Use integer division // so n stays an int.
Show correct code
Peek only after you have tried. You can still Check your own version.
n = int(input())
steps = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
print(steps)
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.