[Shootout-list] Clean nsieve-bits
Diederik van Arkel
dvanarkel@mac.com
Fri, 25 Mar 2005 10:13:19 +0100
--Apple-Mail-17-290813712
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
charset=US-ASCII;
format=flowed
A Clean version of nsieve-bits...
regards,
Diederik van Arkel
--Apple-Mail-17-290813712
Content-Transfer-Encoding: 7bit
Content-Type: application/text;
x-mac-type=54455854;
x-unix-mode=0644;
x-mac-creator=3350524D;
name="nsieve_bits.icl"
Content-Disposition: attachment;
filename=nsieve_bits.icl
// The Great Computer Language Shootout
// http://shootout.alioth.debian.org/
//
// contributed by Diederik van Arkel
module nsieve_bits
import StdEnv, LanguageShootout
Start world
# n = argi
# (io,world) = stdio world
# io = sieve n io
# io = sieve (n-1) io
# io = sieve (n-2) io
# (err,world) = fclose io world
= world
nbits :== 32
all_true :== 0xFFFFFFFF
sieve n io
# m = (1 << n) * 10000
arr = createArray ((m+1)/nbits + 1) all_true
c = loop arr m 2 0
= io <<< "Primes up to " <<< fmt 8 m <<< " " <<< fmt 8 c <<< "\n"
fmt width i
# is = toString i
= toString (repeatn (width - size is) ' ') +++ is
loop :: !*{#Int} !Int !Int !Int -> Int
loop arr m n c
| n == m
= c
| arr.[n >> 5] bitand (1 << (n bitand 31)) <> 0
# arr = update` arr (n+n)
= loop arr m (n+1) (c+1)
= loop arr m (n+1) c
where
update` :: !*{#Int} !Int -> *{#Int}
update` arr i
| i <= m
#! inb = i >> 5
arri = arr.[inb]
arr = {arr & [inb] = arri bitand (bitnot (1 << (i bitand 31)))}
= update` arr (i+n)
= arr
--Apple-Mail-17-290813712--