← Back to Loops
Question 400
Collatz Sequence
Collatz Sequence
Read a positive whole number n and print its Collatz sequence, one value per line, starting with n itself: while the value is not 1, replace it with n // 2 when it is even and with 3 * n + 1 when it is odd (use the remainder operator % to tell them apart), printing each new value. After the final 1 print the length of the sequence in the form Length: <count>, counting both the first value and the final 1. Input: one integer, no prompt. Exactly as in the lecture deck.
Expected Output:
6 3 10 5 16 8 4 2 1 Length: 9
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
LoopsPractice Problems
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Ctrl+Space to expand shortcuts (pr, inp, def)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.