I was playing around with the project euler problem 14.
The solution I came up with is listed below as cf1
. The solution works fine but I get the compiler warning:
Compile::cset: Variable max of type _Integer encountered in assignment of type _Real.
I don't get this message at all since the only assignment of max is max=l
while Head@l == Integer
. This error can be fixed by substituting with max=Round[l]
. Any ideas?
cf1 = Compile[{}, Module[{l, max = 0, maxN = 0},
Do[
l = Length[NestWhileList[If[EvenQ[#], #~Quotient~2, 3 # + 1] &, n, # != 1 &]];
If[l > max, max = l; maxN = n];
, {n, 1, 10^4}];
{max, maxN}
]];
cf1[] // Timing
{6.349241, {262, 6171}}
I also found a solution with much better performance listed below as cf2
. Is it just that NestWhileList
doesn't compile very good or is there another reason why this solution is so much faster?
cf2 = Compile[{}, Module[{n1, l, max = 0, maxN = 0},
Do[
n1 = n;
l = 1;
While[n1 != 1, n1 = If[EvenQ[n1], n1~Quotient~2, 3 n1 + 1]; l++];
If[l > max, max = l; maxN = n];
, {n, 1, 10^4}];
{max, maxN}
]];
cf2[] // Timing
{0.374402, {262, 6171}}
Compile
but this was my solution which I thought was intuitive (warning: it's painfully slow):Clear[euler14]; euler14[n_?EvenQ] := n/2; euler14[n_?OddQ] := 3 n + 1; MaximalBy[{#, Length@NestWhileList[euler14, #, # != 1 &]} & /@ Range[1, 10^4], Last] // Timing (* {2.683217, {{6171, 262}}} *)
. I was surprised that the#
's of theNestWhileList
and one used to map to the list of number (from 1 to 10^4) play nice with each other. $\endgroup$Do
loops really make me go into a tailspin! $\endgroup$