The Collatz conjecture in mathematics asks whether repeating two simple arithmetic operations will eventually transform every positive integer into one. It concerns sequences of integers in which each term is obtained from the previous term as follows:
if the previous term is even, the next term is one half of the previous term.
If the previous term is odd, the next term is 3 times the previous term plus 1.
The conjecture is that these sequences always reach 1, no matter which positive integer is chosen to start the sequence.
You are given an integer n and you should print to the console all the values that n takes throughout the Collatz Conjecture.
Example:
Input: n = 3 Output: 3 10 5 16 8 4 2 1 Explanation: n = 3 => n is odd => n becomes 3 * 3 + 1 = 10 n = 10 => n is even => n becomes 10 / 2 = 5 n = 5 => n is odd => n becomes 5 * 3 + 1 = 16 n = 16 => n is even => n becomes 16 / 2 = 8 n = 8 => n is even => n becomes 8 / 2 = 4 n = 4 => n is even => n becomes 4 / 2 = 2 n = 2 => n is even => n becomes 2 / 1 => 1 n = 1 => stopHints:
Look at the example and notice that we apply a transformation over and over until we reach a final point where we stop. Does that ring a bell?
We need to repeat the transformation code as long as one condition holds (
n is greater than 1). How do you write that in code?
We will use a
while loop that executes as long as n > 1 . What should we do inside this loop?
If
n is even, we should apply a transformation. Otherwise, we should apply the other transformation. How do we handle these different scenarios?
We can do this using an
if - else statement. Video Solution:
Free plan: 30 tutor messages. Premium is unlimited.