Last active
December 26, 2015 11:48
-
-
Save marshall-lee/7146016 to your computer and use it in GitHub Desktop.
Lazy prime numbers in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sqrti x = (truncate . sqrt . fromInteger) x | |
primes = filter (\n -> all (\y -> n `mod` y /= 0) [2..sqrti(n)]) [2..] | |
isPrime x = elem x (takeWhile (<= x) primes) | |
-- ghci> take 10 primes | |
-- [2,3,5,7,11,13,17,19,23,29] | |
-- ghci> take 8 (drop 2 primes) | |
-- [5,7,11,13,17,19,23,29] | |
-- ghci> take 100500 primes | |
-- ... | |
-- ghci> isPrime 1 | |
-- False | |
-- ghci> isPrime 2 | |
-- True | |
-- ghci> isPrime 3 | |
-- True | |
-- ghci> isPrime 16 | |
-- False | |
-- ghci> isPrime 31 | |
-- True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ruby version here