Problem 10, more primes. Sum the all primes under 2,000,000.
Probably meant to force you out of brute force trial division.
Probably want you to use the Sieve Of Eratosthenes.
And I thought about it.
Then tried trial division for fun.
Exactly 1 minute run time.
Done!
Heh.
Looking at future problems, this is probably the last time I can take the easy way out.
Lazy code -
-module(euler10).
-import(math).
-export([sumprimes/1]).
sumprimes(Max) ->
Sum = sum(Max,2,0),
Sum.
sum(Max,Start,Sum) ->
if Start =< Max ->
MaxFactor = math:sqrt(Start),
Prime = isprime(Start,2,MaxFactor),
if Prime == true ->
Newsum = Sum + Start,
sum(Max,Start+1,Newsum);
true ->
sum(Max,Start+1,Sum)
end;
true ->
Sum
end.
isprime(N,PFactor,Max)->
if PFactor =< Max ->
if N rem PFactor == 0 ->
false;
true ->
isprime(N,PFactor+1,Max)
end;
true ->
true
end.

Post a Comment