I wrote isPrime function. It checks if a given number is prime or not. The last "prime" list is given separately.
prime :: [Integer]
prime = 2 : filter isPrime [3..]
isPrime :: Integer -> Bool
isPrime n | n < 2 = False
isPrime n = all (\p -> n `mod` p /= 0) . takeWhile ((<=n) . (^2)) $ prime
I thought it was always better to consolidate two functions into one if possible..so I consolidated isPrime and prime into one function isPrime2. But the isPrime2's performance is very bad.
isPrime2 :: Integer -> Bool
isPrime2 n | n < 2 = False
isPrime2 n = all (\p -> n `mod` p /= 0) . takeWhile ((<=n) . (^2)) $ 2 : filter isPrime2 [3..]
isPrime 40000000000000000001
=> 0.5 second
isPrime2 40000000000000000001
=> 19.8 seconds
My machine is Ubuntu 17.10 x86-64. I am using ghc 8.2.1. Does anyone know why?
prime
is a constant, it gets memoised, whereasisPrime2
is a function, so it doesn't. That's only a guess, however... – RangoonisPrime2 n
asall (\p -> n `mod` p /= 0) . takeWhile ((<=n) . (^2)) $ 2 : [3,5..]
? – Linnemanmod
p /= 0) . takeWhile ((<=n) . (^2)) $ 2 : [3,5..] is very fast... in my machine it took 0.025 second. I also tried all (\p -> nmod
p /= 0) . takeWhile ((<=n) . (^2)) $ [2,3,5]++[6*x+y|x<-[1..],y<-[1,5]], which is slightly faster than 2:[3,5..] – Stroud