3.09.2011

Euler 007


By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?

My solution below.



Lots of ways to skin this cat. Reading about primes seems to suggest that the best way is to use a sieve, as they can be implemented in an elegant (if not resource-efficient) manner.
z=s[2..]s(p:xs)=p:s[x|x<-xs,x`mod`p>0] 
a=z!!10000
51 characters.
This is pretty memory intensive, since it maintains the set of primes as it calculates up to the answer, but it makes subsequent searches much faster.

On a whim, I tried a different, more naive implementation, and it was a lot faster:

p n=let c=round$sqrt$(fromIntegral::Integer->Double) n in all(\x->n`mod`x/=0)[2..c]ps=[x|x<-[2..],p x] 
a=ps!!10000 
Uses more characters, though...117 of them. Algorithmically, this would probably lose out eventually, when we get into the millions of primes, maybe.

No comments:

Post a Comment