The method should work in haskell also. If you try it, please do let me know how much speedup u get, if any.

]]>```
sprimesS :: Int -> Stream Integer
sprimesS n | n == 1 = stream primes
| n > 1 = Stream next (L (sum h,primes,t))
where
(h,t) = splitAt n primes
next (L (s,(x:xs),(y:ys))) = Yield s (L (s-x+y,xs,ys))
sprimes = unstream . sprimesS
```

That should prevent much GC, because all we need is primes list, all other is shifting sums.

]]>I used the following definition of sumN (equivalent to Russel’s function). Should be much faster, since it doesn’t need to iterate through 665 primes for each element.

```
sumN n = sumN' primes (drop n primes) (sum $ take n primes)
sumN' (x:xs) (y:ys) accum = accum:sumN' xs ys (accum+y-x)
```

My definition of primes, btw, is the following. Slower than the fastest one on the quoted page, but still pretty fast and elegant.

```
primes = 2:[x | x <- [3,5..], is_prime x]
is_prime n = all (/= 0) [n `mod` x | x <- takeWhile ((<=n).(^2)) primes]
```

]]>That is a beautiful definition of `sumN`

! I wasn’t aware of the existance of the `tails`

function before.

@Peter,

Thanks for pointing that out, it does make it a bit more beautiful and readable.

]]>`main = print $ head $ foldl1 intersect [sumN n | n <- [1, 3, 29, 373, 665]]`

I really like foobar’s definition of sumN — much better than the one I came up with — although I’d have used zipWith, like this:

```
sumN 1 = primes
sumN (n+1) = zipWith (+) primes $ tail $ sumN n
```

For extra prettiness, notice that primes == sumN 1 and that Andre’s version of intersect can be derived from Magnus’ version of intersect using foldl1:

`main = print $ head $ foldl1 intersect [sumN n primes | n <- [1, 3, 29, 373, 665]]`

`sumN`

as `sumN xs = map (sum . take n) (tails primes)`

]]>My intersection-function is similar, although it finds elements which are in each passed (infinite) list. Here’s my implementation:
```
intersect :: (Eq a, Ord a) => [[a]] -> [a]
intersect [] = []
intersect xs | or (map null xs) = []
| and $ map ((== x) . head) xs = x : (intersect $ map tail xs)
| otherwise = intersect $ map (dropWhile (< max)) xs
where max = let comp (x:
```

(Sorry for the formatting.)*) (y:*) = compare x y
in head $ maximumBy comp xs
x = head $ head xs

Therefore I’ve a more general function for finding the prime which fulfills the required conditions:
```
prime :: [Int] -> Integer
prime = head . intersect . (primes:) . map (`calc` primes)
```

Whereas calc is semantically equivalent to your sumN-function.

Using your test-data and the optimized sieve my program needs circa 10 seconds for finding the solution. Great work of yours!

]]>