Google Treasure Hunt primes question
- Magnus Therning
In the comments to my post on the Google treasure hunt Andre asked me to put up my solution for the fourth problem. The problems were personalised and here is mine:
Find the smallest number that can be expressed as
the sum of 3 consecutive prime numbers,
the sum of 29 consecutive prime numbers,
the sum of 373 consecutive prime numbers,
the sum of 665 consecutive prime numbers,
and is itself a prime number.
The idea behind my solution is that if I have four lists of the sums, and a list of primes, then the solution to the problem is the smallest member of the intersection of all five lists.
I saved the problem of finding primes to the last and instead concentrated on summing up lists of integers in a convenient way. I ended up with the following solution to that:
sumN :: Int -> [Integer]
sumN n = map fst sumi
where
sumi = tail $ iterate (sumn) (0, primes)
sumn (r, xs) = (sum $ take n xs, tail xs)
The real work happens in the inner functions. sumn
picks out as many numbers as I want and sums them up, the reason for taking and returning a tuple is that sumi
can use iterate
to calculate the sequence of sums. The first item in the result of iterate a
is a
, so sumi
drops the first one. This lets me create the needed lists of sums:
sum3 = sumN 3
sum29 = sumN 29
sum373 = sumN 373
sum665 = sumN 665
After having a quick look at the implementation of Data.List.intersect I realised it probably would be a bit too slow. Instead I wrote one that exploits that all the involved lists are ordered:
intersection a@(x:xs) b@(y:ys)
| x == y = x : intersection xs ys
| x < y = intersection (dropWhile (< y) xs) b
| x > y = intersection a (dropWhile (x >) ys)
After convincing myself that this code did what I wanted (basically through playing in GHCi using an incorrect definition of primes, primes = [1..]
) I turned to the problem of finding the primes. Of course someone else had already written the Haskell code to find primes. That code fitted perfectly with mine since it produces an infinate list of Integer
s. Brilliant! :-)
Finally here’s the main
that allows me to compile the code and get the answer quickly (it’s slightly modified for the medium, basically I wrote it all on one, long line):
main :: IO ()
main = let
i1 = (primes `intersection` sum665)
i2 = (sum3 `intersection` sum373)
s = i1 `intersection` i2 `intersection` sum29
in
print $ head s
Compiled, it runs in about 5.5 seconds on my desktop machine.