I am new to the language and trying to solve Euler Problem 10 (http://projecteuler.net/):- "What is the sum of all primes below 2 million?"
I thought that this was a neat answer:-
let getPrimes1 (max) =
let primes = new BitArray(max+1, true)
[ for n in [2..max] do
if primes.[int n] then
for i in [int64 n * int64 n..int64 n..int64 max] do primes.[int i] <- false
yield n ]
let solve1 () =
getPrimes1 2000000 |> Seq.fold (fun acc itm -> int64 itm + acc) 0L
However, the performance was appalling. This function used over 200MB of heap and took around 6 secs to execute on my laptop. I refactored as below and the new version takes .2 secs and uses 1MB heap. However it looks awful! What am I doing wrong and what is the elegant solution?
let getPrimes max =
let primes = new BitArray(max+1, true)
let result = new ResizeArray<int>(max/10)
for n = 2 to max do
if primes.
then
let start = (int64 n * int64 n)
if start < int64 max then
let i = ref (int start)
while !i < max do primes.[!i] <- false; i := !i + n
result.Add n
result