Follow the rule
Here is a famous game. Pick any whole number. If it is even, halve it. If it is odd, triple it and add 1. Then do the same again with the new number, and carry on until you reach 1.
Start with 6: it goes 6, 3, 10, 5, 16, 8, 4, 2, 1. That's 8 steps. Start with 7 and it takes 16 steps. Nobody has found a formula that tells you how many steps there will be in advance. You just follow the rule.
- n
- 6
- steps
- 0
Start at 6. It is even, so halve it.
A loop that decides as it goes
This is where a while loop shines. A for loop needs to know its length at the start. But here only the numbers themselves tell you when to stop.
So the loop condition is simply "not at 1 yet". Inside, you choose between two updates with an if and else, and count each step. Always check that your loop is heading towards its end. Here every number is eventually brought back to 1.
steps = 0
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
steps = steps + 1