98. Python Program to Count the Steps of the Collatz Sequence
Mediumwhile or for
Overview
A famous puzzle where nobody knows in advance how many rounds the loop will take: a clear job for while.
Problem Statement
Read a whole number n (1 or more). Print it, then repeat these steps until n is 1:
- if
nis even, divide it by 2 (use//); - if
nis odd, multiply it by 3 and add 1.
Print each new value of n on its own line. At the end, print how many steps it took. For example, for 6:
6
3
10
5
16
8
4
2
1
Steps: 8
For 1, print 1 and Steps: 0.
Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Input
One value per line. Example:
6
Output
The output for that example:
6
3
10
5
16
8
4
2
1
Steps: 8
The tests try 4 different inputs.