Good observation! It looks like Fermat's method (the method I
mentioned above) doesn't necessarily find all, or even any
of the factors. It is just a heuristic. On the other hand,
if you have an even number, you may extract factors of 2 until
you get an odd number, in which case (x+y) and (x-y) must
both be necessarily odd.
The generalization that gumby mentioned, x^2 = y^2 (mod p)
may have more sucess, but I don't know if it is exhaustive.
Here is code that implements it:
my $p = shift;
my %residues;
my %factors;
foreach my $x (2..$p) {
my $mod = ($x*$x) % $p;
if (exists $residues{$mod}) {
$factors{$x-$residues{$mod}}++ if $p % ($x-$residues{$mod}) == 0
+;
$factors{$x+$residues{$mod}}++ if $p % ($x+$residues{$mod}) == 0
+;
}
else {
$residues{$mod} = $x;
}
}
foreach (sort {$a <=> $b} keys %factors) {
print "$p = $_*", $p/$_, "\n";
}
For 54, this yields
1021% factor.pl 54
54 = 2*27
54 = 6*9
54 = 18*3
54 = 54*1
But this code is unsatisfying because it takes longer
than the simple trial by division. Thinking from a divide
and conquer point of view, it is probably faster to use
these methods to find a factorization, then recursively
find factorizations of the factors untill all are prime.
-Mark
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.