Create a function to determine the length of a sequence of numbers obtained via the Collatz conjecture, ending at ::1::.




One of the simplest yet extremely complicated to prove concepts in mathematics is that of the Collatz conjecture, proposed in 1937 by Lothar Collatz.

It's known as a conjecture (contrary to a theorem) because over all these years of mathematical revolution, no one has been able to prove it. Yes, no one!

The Collatz conjecture can be described as follows:

Take any positive integer ::n::. If it's even, divide it by ::2:: to obtain the next integer. Or else, multiply by ::3:: and then add ::1:: to obtain the next integer. Continue this process.

It's widely believed that for any starting integer, the whole sequence of integers eventually reaches ::1::.

And this is the conjecture: that we'd eventually reach the integer ::1:: no matter which starting integer we use.

The Collatz conjecture has been tested for a humongous array of numbers. It has been shown that the conjecture holds for all positive integers approximately up to the value ::2^{68}:: (that's a huge huge huge number!).

Anyways, let's consider some examples.

Here's the sequence of integers starting at ::3::, up to the point we reach ::1:::


Here's the sequence of integers starting at ::17::, once again up to the point we reach ::1:::


Here's the sequence of integers starting at ::30:::


And you can try it for any other positive integer yourself! See how far does the sequence go.

Now consider the sequence of integers starting at a given positive integer ::n:: and ending at ::1::, whereby every subsequent element is obtained by performing the rules mentioned above. The length of this sequence is simply the total number of elements in the sequence.

For instance, the length of the sequence that begins at ::3:: is ::8:: (as there are a total of 8 elements in it). Similarly, the length of the sequence that begins at ::17:: is ::13::.

In this exercise, you have to create a function called collatzLength() that takes in the starting value of the sequence as an argument and returns back its length.

Note that if the provided argument is any of the following, the function must return null:

  • Not a number, for e.g. 'Hello'.
  • The special number NaN.
  • The special numbers +Infinity or -Infinity.
  • A non-integral number, for e.g. 10.2.
  • Not a positive integer, for e.g. 0, -1.

Here's an example of its usage: