I'm VERY new to Mathematica programming (and by new I mean two days), and was solving Project Euler question 12, which states:
Which starting number, under one million, produces the longest [Collatz] chain?
Now don't take this question wrong. I am not asking for a solution, I am simply wondering why my proposed solution is taking so long to produce an answer. It does eventually produce the correct solution to the problem.
My code is below:
collatzLength[x_] := Module[{c, n}, (For[n = x; c = 1, n != 1, c += 1,
If[EvenQ[n], n = n/2, n = 3*n + 1]]); c]
Last@Flatten@(MaximalBy[Transpose@{(collatzLength /@
Range[1000000]), Range[1000000]}, First])
It seems that the collatzLength /@ Range[1000000] is what is taking so long, so I am wondering how I can improve the collatz function (or any of the code) so that it completes in a reasonable timeframe.