Problem Description: The Collatz Conjecture states that for any natural number n, if n is even, divide it by 2.
If n is odd, multiply it by 3 and add 1. If you repeat the process continuously for n, n will eventually reach 1.
For example, if n = 20, the resulting sequence will be:
[20, 10, 5, 16, 8, 4, 2, 1]
Write a program that will output the length of the Collatz Conjecture for any given n. In the example above, the output would be 8.
Level: 7kyu
Link to Kata: Collatz Conjecture Length
This was a pretty simple Kata. I used a while condition where I checked every time for the value of n and continue going through the loop until the value of is not equal to 1. I also initialized an empty array col_a to store different variations n goes through before it becomes 1. In the loop if n is an even number I changed the value of n to n/2 according to the conjecture and if n was odd I multiplied n by 3 and added 1 to the product. In both the cases I pushed the new value of n to the col_a array.
Once n becomes 1 and exits out of the while loop, I calculate the value of length of col_a array and add 1 to it. (Adding 1 because we consider the initial value of n and it will also be part of the array.)
We return the final value which will give us the length of the Collatz Conjecture for any given n.
If you want to do some further reading on Collatz Conjecture then here is the link: Collatz Conjecture
Here is a link to the code: Kata Day 4
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment