Skip to content

Instantly share code, notes, and snippets.

@marshall-lee
Last active December 26, 2015 11:48
Show Gist options
  • Save marshall-lee/7146016 to your computer and use it in GitHub Desktop.
Save marshall-lee/7146016 to your computer and use it in GitHub Desktop.
Lazy prime numbers in Haskell
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
@marshall-lee
Copy link
Author

Ruby version here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment