Not to be overly nitpicky, but this does not produce prime factors with any certainty. The first factor it provides is prime, the second only rarely is prime. So once you get the first prime factor, you have to run the second factor through this again until the second return value is 1.
Update: I somehow missed the part of the RSA challenge where they stated that the numbers they pose have only two prime factors, and for that, there indeed would be no need to calculate past one iteration.
And just so I'm not whining without contributing, here's a look at obtaining all the factors with the modulus routine. ;)
#!/usr/bin/perl -w
use strict;
#note that this code is brutally slow
my $number = shift; #assume user knows to input a number
my @all_factors = factor( $number );
my $check_factor = 0;
while ($check_factor != 1 )
{
$check_factor = pop @all_factors;
push( @all_factors, factor( @check_factor ) );
}
if( @all_factors + 0 == 1 )
{
print "$number is prime\n";
}
else
{
print "$number: " .join( ',', @all_factors ). "\n";
}
exit;
sub factor
{ #one slight change to prevent an illegal modulus operation
my $n; my $p;
$n=$p=pop;
return if( $n ==1 );
1 while $n%--$p;
$n/$p,$p;
}
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.