2012-04-19

Prime numbers in Haskell

Hello again,
last night I couldn't sleep very well, so I tried a new method to calculate prime numbers(from 2 to n), this time in haskell.
I'm not exactly sure on the runtime, i guess O(n^2), maybe lower, but it's hard for me to say, because I believe it depends on the distribution of the prime numbers themselves. But I'm thankfull if anyone wants to analyze this and tell me :)


calcprimes :: Int -> [Int]
calcprimes n = primeh [2..n] []
 where primeh :: [Int] -> [Int] -> [Int]
primeh [] primes = reverse primes
primeh (x:xs) primes = primeh (primeh2 x xs [] ) (x:primes)
where primeh2 :: Int -> [Int] -> [Int] -> [Int]
primeh2 _ [] ys = reverse ys
primeh2 d (x:xs) ys = if mod x d == 0
                                      then primeh2 d xs ys
                                      else primeh2 d xs (x:ys)


UPDATE 1: Woops, it seems I accidentally reinvented (or remembered and just didn't know I saw this this before) the wheel, erm I mean the "Sieve of Eratosthenes" and also that there are shorter implementations of this, which can also handle infinite data structures and stuff - "much more to learn to I have..."


UPDATE 2: With a little lambda magic and "filter" I wrote a little shorter and even faster version of this:



calcprimes :: Int -> [Int]
calcprimes n = primeh [2..n] []
 where  primeh :: [Int] -> [Int] -> [Int]
        primeh [] primes = reverse primes
        primeh (x:xs) primes = primeh (filter (\y -> mod y x /= 0) xs) (x:primes)

No comments:

Post a Comment