Algorithmic efficiency and golf are not good friends. 33 chars, assuming you only want two prime factors:
| | sub factor {
$n=$p=pop;1while$n%--$p;$n/$p,$p;
}
|
Update: Thanks to CheeseLord for pointing out that the trailing semicolon on this golf is entirely unnecessary, without merit, sans raison d'etre, serving absolutely no purpose, whatsoever, amen.
MeowChow
s aamecha.s a..a\u$&owag.print | [reply] [d/l] |
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;
}
| [reply] [d/l] |
MeowChow
s aamecha.s a..a\u$&owag.print | [reply] [d/l] |
Well, you only need one number since the RSA numbers are factors of 2 primes.
Oh Yeah, and you only need every other number, since you know that it isn't prime if it's even.
Also, you don't need to count for 2, because you can check to see if the last number is even, and then the challenge wouldn't be very hard.
$p=<the number>;$r=3;while((p%r)!=0)r+=2; <==Unreadably
**READABLY**
$p=<the number>;
$r=3;
while((p%r)!=0)r+=2;
**READABLY**
Not such a bad solution character count wise.
Just Another Perl Backpacker
| [reply] |