The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
import math, strutils
var is_prime: seq[Bool] = @[]
is_prime.add(False)
iterator iprimes_upto(limit: int): int =
for n in high(is_prime) .. limit+2: is_prime.add(True)
for n in 2 .. limit + 1:
if is_prime[n]:
yield n
for i in countup((n *% n), limit+1, n): # start at ``n`` squared
try:
is_prime[i] = False
except EInvalidIndex: break
echo("Primes are:")
for x in iprimes_upto(200):
write(stdout, x, " ")
writeln(stdout,"")
jrs@laptop:~/nimrod/examples$ nimrod c -d:release sieve.nim
config/nimrod.cfg(36, 11) Hint: added path: '/home/jrs/.babel/libs/' [Path]
Hint: used config file '/home/jrs/nimrod/config/nimrod.cfg' [Conf]
Hint: system [Processing]
Hint: sieve [Processing]
Hint: math [Processing]
Hint: strutils [Processing]
Hint: parseutils [Processing]
gcc -c -w -O3 -fno-strict-aliasing -I/home/jrs/nimrod/lib -o examples/nimcache/sieve.o examples/nimcache/sieve.c
gcc -c -w -O3 -fno-strict-aliasing -I/home/jrs/nimrod/lib -o examples/nimcache/system.o examples/nimcache/system.c
gcc -c -w -O3 -fno-strict-aliasing -I/home/jrs/nimrod/lib -o examples/nimcache/math.o examples/nimcache/math.c
gcc -c -w -O3 -fno-strict-aliasing -I/home/jrs/nimrod/lib -o examples/nimcache/strutils.o examples/nimcache/strutils.c
gcc -o /home/jrs/nimrod/examples/sieve examples/nimcache/parseutils.o examples/nimcache/strutils.o examples/nimcache/math.o examples/nimcache/system.o examples/nimcache/sieve.o -ldl -lm
Hint: operation successful (9489 lines compiled; 1.661 sec total; 11.117MB) [SuccessX]
jrs@laptop:~/nimrod/examples$ time ./sieve
Primes are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
real 0m0.002s
user 0m0.000s
sys 0m0.000s
jrs@laptop:~/nimrod/examples$