Faffing round the edges Its easier than getting stuck in

28Dec/080

Problem 10: Sum of the Primes

I haven't posted for a while. I'm contracting for a VoD producing company pathologically averse to normal quality measures which has taken all (ALL) my time.

Anyway, the problem:

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Since I already have a functional prime checker from problem 3 so the code is just:

prob10_alt(N) ->
	Primes = [A || A <- lists:seq(3, N, 2), is_prime2(A)],
	lists:sum([2|Primes]).

I know this isn't the Sieve of Eratosthenes but I had a crack at a sieve implmentation and it was pitifully slow compared to the above. I know it is not optimal but it is adequate. I did learn about The Sieve due to this problem so it was of benefit. I have also read and implemented a Java version of The Sieve (it really suits iteration) so education has occurred.

In case anyone reads this and can help me with my Sieve versions here it is:

prob10_sieve2(N) ->
	Limit = floor(math:sqrt(N)),
	Cans = array:new(N, {default, true}),
	Cans2 = seive_it(4, N, 2, Cans),
	Primes = seive2(Cans2, Limit),
	array:foldl(fun(X, Val, Acc) -> arr_fold_fun(X, Val, Acc) end, 0, Primes) - 1.

arr_fold_fun(X, Val, Acc) ->
	case Val of
		true ->
			X + Acc;
		false ->
			Acc
		end.

seive2(Array, Limit) ->
	for(3, Limit, 2, Array).

for(Start, Limit, _Step, Array) when Start >= Limit -> Array;
for(Start, Limit, Step, Array) ->
	case array:get(Start, Array) of
		true ->
			for(Start+Step, Limit, Step,
                             seive_it(Start*Start, array:size(Array), 2*Start, Array));
		false ->
			for(Start+Step, Limit, Step, Array)
		end.

seive_it(Start, Limit, _Step, Array) when Start >= Limit -> Array;
seive_it(Start, Limit, Step, Array) ->
	seive_it(Start+Step, Limit, Step, array:set(Start, false, Array)).
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

You must be logged in to post a comment.

No trackbacks yet.

 

December 2008
M T W T F S S
« Nov   Mar »
1234567
891011121314
15161718192021
22232425262728
293031  

Archives