Skip to content

Instantly share code, notes, and snippets.

@rik0
Created August 25, 2011 18:46
Show Gist options
  • Save rik0/1171446 to your computer and use it in GitHub Desktop.
Save rik0/1171446 to your computer and use it in GitHub Desktop.
Monadic Eratosthenes Sieve
import System.Environment
import Control.Monad
import Data.Array
import Data.Array.ST
(^!) :: Num a => a -> Int -> a
(^!) x n = x^n
squareRoot :: Integer -> Integer
squareRoot 0 = 0
squareRoot 1 = 1
squareRoot n =
let twopows = iterate (^!2) 2
(lowerRoot, lowerN) =
last $ takeWhile ((n>=) . snd) $ zip (1:twopows) twopows
newtonStep x = div (x + div n x) 2
iters = iterate newtonStep (squareRoot (div n lowerN) * lowerRoot)
isRoot r = r^!2 <= n && n < (r+1)^!2
in head $ dropWhile (not . isRoot) iters
erat stop = runSTArray $
newArray (2, stop) True >>=
\sieve -> (mapM_ (\idx -> readArray sieve idx >>=
\isPrime -> when isPrime $
mapM_ (\k -> writeArray sieve k False)
[idx*2, idx*3 .. stop])
[2..stop] >>
return sieve)
primes max = [n | (n, isPrime) <- assocs (erat max), isPrime]
main = do
args <- getArgs
let maxPrime :: Integer
maxPrime = read (head args)
let allPrimes = primes maxPrime
print $ length allPrimes
erat stop = runSTArray $ do
sieve <- newArray (2, stop) True
forM_ [2..stop] $ \idx ->
do
isPrime <- readArray sieve idx
when isPrime $
forM_ [idx*2, idx*3 .. stop] $ \k ->
writeArray sieve k False
return sieve
erat stop = runSTArray $
newArray (2, stop) True >>=
\sieve -> (mapM_ (\idx -> readArray sieve idx >>=
\isPrime -> when isPrime $
mapM_ (\k -> writeArray sieve k False)
[idx*2, idx*3 .. stop])
[2..stop] >>
return sieve)
primes max = [n | (n, isPrime) <- assocs (erat max), isPrime]
import Data.PSQueue
import Data.Maybe
import Control.Monad.State
import System.Environment
heappush :: (Ord k, Ord p) => k -> p -> State (PSQ k p) ()
heappush k p = state $ \pq -> ((), insert k p pq)
heapadjust :: (Ord k, Ord p) => k -> (p -> p) -> State (PSQ k p) ()
heapadjust k f = state $ \pq -> ((), adjust f k pq)
heapview :: (Ord k, Ord p) => State (PSQ k p) (k, p)
heapview = state $ \pq -> let Just b = findMin pq
k = key b
p = prio b
in ((k, p), pq)
heappop :: (Ord k, Ord p) => State (PSQ k p) (k, p)
heappop = state $ \pq -> heappop' pq
where heappop' :: (Ord k, Ord p) => PSQ k p -> ((k, p), PSQ k p)
heappop' pq = let Just (b, pq') = minView pq
in ((key b, prio b), pq')
increasePegs :: Integer -> State (PSQ Integer Integer) ()
increasePegs n = do
(k, m) <- heapview
when (m == n) $
heapadjust k (+k) >>
increasePegs n
primesStep :: Integer -> State (PSQ Integer Integer) (Maybe Integer)
primesStep n = do
(k, m) <- heapview
if m == n
then increasePegs n >>
return Nothing
else heappush n (n*n) >>
return (Just n)
primes = let pq = singleton 2 4
(ps, pq') = (runState $ mapM primesStep [3..]) pq
in catMaybes ps
main = do
args <- getArgs
let maxPrime :: Integer
maxPrime = (read . head) args
print . length $ takeWhile (<maxPrime) primes
-- herat.cabal auto-generated by cabal init. For additional options,
-- see
-- http://www.haskell.org/cabal/release/cabal-latest/doc/users-guide/authors.html#pkg-descr.
-- The name of the package.
Name: herat
-- The package version. See the Haskell package versioning policy
-- (http://www.haskell.org/haskellwiki/Package_versioning_policy) for
-- standards guiding when and how versions should be incremented.
Version: 0.1
-- A short (one-line) description of the package.
Synopsis: Eratosthenes implementations
-- A longer description of the package.
-- Description:
-- URL for the project homepage or repository.
Homepage: https://gist.github.com/1171446
-- The license under which the package is released.
License: BSD3
-- The file containing the license text.
License-file: LICENSE
-- The package author(s).
Author: Enrico Franchi
-- An email address to which users can send suggestions, bug reports,
-- and patches.
Maintainer: enrico.franchi@gmail.com
-- A copyright notice.
Copyright: Enrico Franchi (c) 2011
Category: Math
Build-type: Simple
-- Extra files to be distributed with the package, such as examples or
-- a README.
-- Extra-source-files:
-- Constraint on the version of Cabal needed to build this package.
Cabal-version: >=1.2
Executable erat
Main-is: erat.hs
Build-depends: base, array
Executable ferat
Main-is: ferat.hs
Build-depends: base, PSQueue >= 1.1, mtl
Copyright (c)2011, Enrico Franchi
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Enrico Franchi nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import System.Environment
import Control.Monad
import Data.Array
import Data.Array.ST
(^!) :: Num a => a -> Int -> a
(^!) x n = x^n
squareRoot :: Integer -> Integer
squareRoot 0 = 0
squareRoot 1 = 1
squareRoot n =
let twopows = iterate (^!2) 2
(lowerRoot, lowerN) =
last $ takeWhile ((n>=) . snd) $ zip (1:twopows) twopows
newtonStep x = div (x + div n x) 2
iters = iterate newtonStep (squareRoot (div n lowerN) * lowerRoot)
isRoot r = r^!2 <= n && n < (r+1)^!2
in head $ dropWhile (not . isRoot) iters
erat stop = runSTArray $ do
sieve <- newArray (2, stop) True
forM_ [2..stop] $ \idx ->
do
isPrime <- readArray sieve idx
when isPrime $
forM_ [idx*2, idx*3 .. stop] $ \k ->
writeArray sieve k False
return sieve
primes max = [n | (n, isPrime) <- assocs (erat max), isPrime]
main = do
args <- getArgs
let maxPrime :: Integer
maxPrime = read (head args)
let allPrimes = primes maxPrime
print $ length allPrimes
import Distribution.Simple
main = defaultMain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment