in reply to Quick search for modest numbers of prime numbers
I haven't pushed the primes into their own array. In the end @bits encodes the primes, and the creation of a separate array of primes amounts to needless replication. (Of course you can still create the array of primes on the fly if you so desire - it's not massively expensive in terms of time.)use warnings; use strict; my $t0 = time; my $to_find = 100000; my $allowance = 0.6; my $max = int($to_find * log($to_find) * $allowance); my $count = 1; my $imax = sqrt($max * 2 + 1) + 1; $imax -= 1; $imax /= 2; my @bits = (1) x $max; $bits[0] = 0; for(my $i = 0; $i < $imax; $i++) { if($bits[$i]) { my $k = $i * 2 + 1; for(my $j = $k + $i; $j < $max; $j += $k) { $bits[$j] = 0; } } } my $t1 = time; for(my $i = 0; $i < $max; $i++) { if($bits[$i]) { $count++; print $i * 2 + 1, " "; if($count == $to_find){last} } } print "\nFound at least $count primes in ", $t1 - $t0, " seconds\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Quick search for modest numbers of prime numbers
by johngg (Canon) on Feb 06, 2006 at 10:09 UTC |