Back to questions
Given a positive integer , the Collatz sequence for is generated by repeatedly applying the following operations:
Your task is to return the number of steps required to reduce to 1.
Input:
Output: 7
Explanation:
The output is 7, because there were 7 Collatz steps taken:
3 ─> 10 ─> 5 ─> 16 ─> 8 ─> 4 ─> 2 ─> 1
Here's the math behind the 7 steps:
Given 3 is odd, so
Given 10 is even, so
Given 5 is odd, so
Given 16 is even, so
Given 8 is even, so
Given 4 is even, so
Given 2 is even, so
Here's an iterative solution that repeatedly applies the Collatz operations until the given number becomes 1, incrementing a count for each operation performed.
Not Just at Bloomberg, but other tech companies too, interviewer ask you to solve the question using multiple approaches. Or at least mention the different althernatives.
Here is a recursive solution to calculate the Collatz Steps;
In case you are not familiar with Recursion, you can find more information here