in reply to Simple primality testing
Well, about the onlything I can add is that I looked into Knuth's AoP and found algoithm P (1.3.2) which is for calculating the first N primes. I found it interesting as it was bit hard to convert the pseudocode* he had to perl. I switched around your code to do the same, and here they are:
sub make_primes_ambrus { my $count=shift; my @primes=(2); my( $n, $p, $sqrp); NLOOP: for ($n=3; @primes<$count; $n+=2) { $sqrp = sqrt($n) + 0.5; for $p (@primes) { $sqrp < $p and last; 0 == $n % $p and next NLOOP; } push @primes, $n } return \@primes; } sub make_primes_knuth { my $count=shift; my @primes=(2); my $n=3; PRIME: while (@primes<$count) { push @primes,$n; while ( $n+=2 ) { for my $p (@primes) { my $r=$n % $p; last if !$r; # According to Knuth the proof of the vaildity # of the following test "is interesting and a little # unusual". next PRIME if int($n/$p) <= $p; } } } return \@primes; }
Incidentally, part of the issue for my original problem is that im generating a random prime relatively rarely, and as a fresh process every time. So the time (and hassle coding) to produce a table of primes to use for the div technique is not really necessary. Doing a brute force check on each random number in turn is just fine for me here.
* (Incidentally is there any easy way to get $Q and $R from $x/$y where Q is the quotient and R is the remainder? I used $Q=int($x/$y); and $R=$X % $Y; but i wonder if there is a better way, obviously repeated subtraction would leave an integer remainer somewhere, but given todays chip design is that actually more efficient than doing div and mod as seperate tasks? )
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Simple primality testing
by ambrus (Abbot) on Nov 23, 2005 at 09:45 UTC |