The Collatz conjecture is one of the most famous one. Take any positive integer n, if it is even divide it by 2, if it is odd multiply it by 3 and add 1 and continue indefinitely.The conjecture is that whatever is n the sequence will reach 1. There is many ways to approach this problem, each one of them had given beautifull graphs and impressive display of calculation power. The simplest approach can be found in this kata: http://www.codewars.com/kata/5286b2e162056fd0cb000c20 You look at the Collatz sequence of a number and see when it reaches 1.
In this kata we will take a look at the length of collatz sequences. And how they evolve. Write a function that take a positive integer n and return the number between 1 and n that has the maximum Collatz sequence length and the maximum length. The output has to take the form of an array [number, maxLength] For exemple the Collatz sequence of 4 is [4,2,1], 3 is [3,10,5,16,8,4,2,1], 2 is [2,1], 1 is [1], so MaxCollatzLength(4)
should return [3,8]
. If n is not a positive integer, the function have to return [].
- As you can see, numbers in Collatz sequences may exceed n.
The last tests use random big numbers so you may consider some optimisation in your code:
You may get very unlucky and get only hard numbers: try submitting 2-3 times if it times out; if it still does, probably you need to optimize your code more;
Optimisation 1: when calculating the length of a sequence, if n is odd, what 3n+1 will be ?
Optimisation 2: when looping through 1 to n, take i such that i<n/2, what will be the lenght of the sequence for 2i ?