proc sieve =
const
n = 10000000;
var
primes: array[n, bool]
for x in primes.mitems: x = true
primes[0] = false
primes[1] = false
var step = 0
while true:
step += 1
while not primes[step]:
step += 1
var startval = step * step;
if startval >= n:
break
for i in countup(startval, n - 1, step):
primes[i] = false
for i in 0..<n:
if primes[i]:
echo i
sieve()
For n=100 it seems to work, but for n=1e7 as above I get "Segmentation fault" for debug build. Nim Compiler Version 0.11.3 (2015-08-11) [Linux: amd64] (Of course there are more beautiful Sieve examples available for Nim, one is at Rosetta code. And generally we would use a sequence, not a fixed sized array. I tried only a very stupid C++ to Nim conversion. Maybe even c2nim would give nicer Nim code ;-) )
the original C++ code from #include <iostream> #include <vector> int main() { const int n = 10000000; std::vector<bool> primes(n, true); primes[0] = primes[1] = false; // Sieb des Erastosthenes int step = 0; while(true) { while(!primes[++step]); // nächste Primzahl suchen int startval = step * step; if(startval >= n) break; for(int i=startval; i<n; i+=step) primes[i] = false; } // Gefundene Primzahlen zur kontrolle ausgeben /* for(int i=0; i<n; ++i) { if(primes[i]) std::cout << i << '\n'; } */ return 0; }