Haskell 010

This commit is contained in:
Correl Roush 2011-10-12 16:56:34 -04:00
parent 71824cf748
commit 03097ec64d
3 changed files with 28 additions and 14 deletions

15
haskell/Util/Primes.hs Normal file
View file

@ -0,0 +1,15 @@
module Util.Primes where
is_prime :: (Integral a) => a -> Bool
is_prime n
| n == 1 = False
| n < 4 = True
| n `rem` 2 == 0 = False
| n < 9 = True
| n `rem` 3 == 0 = False
| otherwise = do
let f = sqrt (fromIntegral n)
let checkprime x = (n `rem` x == 0 || n `rem` (x + 2) == 0)
not (or (map checkprime (takeWhile (<= floor f) [5,11..])))
primes = filter is_prime (2:[3,5..])

View file

@ -5,20 +5,7 @@ What is the 10001st prime number?
-} -}
import Text.Printf import Text.Printf
import Util.Primes (primes)
is_prime :: (Integral a) => a -> Bool
is_prime n
| n == 1 = False
| n < 4 = True
| n `rem` 2 == 0 = False
| n < 9 = True
| n `rem` 3 == 0 = False
| otherwise = do
let f = sqrt (fromIntegral n)
let checkprime x = (n `rem` x == 0 || n `rem` (x + 2) == 0)
not (or (map checkprime (takeWhile (<= floor f) [5,11..])))
primes = filter is_prime (2:[3,5..])
main = do main = do
printf " 6th prime: %d\n" (primes !! 5 :: Integer) printf " 6th prime: %d\n" (primes !! 5 :: Integer)

12
haskell/e010.hs Normal file
View file

@ -0,0 +1,12 @@
{- Calculate the sum of all the primes below two million.
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
-}
import Text.Printf (printf)
import Util.Primes (primes)
main = do
printf "Sum of primes below 10: %d\n" (sum (takeWhile (<10) primes))
printf "Sum of primes below 2,000,000: %d\n" (sum (takeWhile (<2000000) primes))