For larger numbers, say:
66_666_666_666_666_666_666_666_666_666_666_666_666_667 you can use use some tricks that will proves that a number is composite. Here is a script that gives a better that 50% chance that a number is prime. By looping you can reduce the chance that a number is that not prime is reported as prome. 10 loops gives a 1 in 2^10 chance of being wrong.
#!/usr/bin/perl
use strict;
use Math::BigInt::GMP;
# Precondition: a, n >= 0; n is odd
use strict;
use warnings;
#use diagnostics;
use Crypt::OpenSSL::Random;
use Data::Dumper;
use Math::BigInt;
use Math::BigFloat;
sub brand {
my $number = shift;
my $n = Math::BigInt->new($number);
my $l = Math::BigFloat->new($n + 1)->blog(2)->bceil;
my $r = 0;
while ($r == 0 or $r >= $n) {
my $x = Crypt::OpenSSL::Random::random_pseudo_bytes(10);
$r = Math::BigInt->new('0b' . unpack("B$l", $x));
if ($r < $n and $r) {
last;
} else {
# printf "rand miss\n";
}
}
return $r;
}
sub jacobi
{
my ($a, $n) = @_;
die unless defined $a;
if ($a == 0) { # identity 1
return ($n == 1) ? 1 : 0;
}
if ($a == 2) { # identity 2
my $x = $n % 8;
if ($x == 1 || $x == 7) {
return 1;
} elsif ($x == 3 || $x == 5) {
return -1;
}
}
if ( $a >= $n ) { # identity 3
return jacobi($a % $n, $n);
}
if ($a % 2 == 0) { # identity 4
return jacobi(2, $n) * jacobi($a/2, $n);
}
die if $a % 2 == 0;
# identities 5 and 6
return ($a % 4 == 3 && $n % 4 == 3) ? -jacobi($n, $a) : jacobi($n, $
+a);
}
sub check
{
my $number = shift;
my $n = Math::BigInt->new($number);
return 'Composite 0' if $n->copy->bmod(2) == 0;
my $a = 0;
while ($a == 0) {
$a = brand($number);
}
return 'Composite 1' if (1 != $a->copy->bgcd($n));
my $x = ($n - 1) / 2;
my $q = $a->copy->bmodpow($x, $n);
# die 'bad math' unless $q == $q_p;
my $j = jacobi($a, $n);
$j %= $n;
if ($j == $q) {
return 'Prime.';
} else {
return 'Composite 2';
}
}
my $number = shift || die "Need a number.";
my $loops = shift || 10;
die if ($loops < 0);
my $c = 0;
while ($c++ < $loops) {
my $ret = check($number);
if ($ret =~ /Composite/) {
print $ret, "\n";
exit;
}
}
print "This is only a 1/2^", $loops, " chance that $number is not prim
+e\n";
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|