OK, the problem occurred when I challenged with Project Euler No. 10
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.
My code is:
ClearAll[primelist, i]
primelist = {}; i = 1
While[Prime[i] < 2*10^6, AppendTo[primelist, Prime[i]];i++]
Plus @@ primelist
And I get the answer correct.
I think using While
is not a good habit in functional programming, but I can not modify my code to NestWhileList
(or others FP-like functions).
One of the proper manner is:
Plus @@ (Prime /@ NestWhileList[# + 1 &, 1, (Prime[# + 1] < 2*10^6 &)])
But I think it is not efficient, because when evaluating the NestWhileList
,
Prime[1],Prime[2],Prime[3],...
ran the first time(in order to compare with 2*10^6), and then when mapping Prime to the list which was the result of NestWhileList
, the same thing went once again!
MMA evaluate Prime[1],Prime[2],Prime[3],...
one more time.
- Is there any method (or SOP) that can always change
While
toNestWhile
orNestWhileList
? - And I found that the second code above run faster much more than code 1, unbelievable.