in reply to RSA Factoring challenge

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

Replies are listed 'Best First'.
(ichimunki) Re x 2: RSA Factoring challenge
by ichimunki (Priest) on Jul 26, 2001 at 02:27 UTC
    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; }
      What I meant, which I suppose could have been stated more clearly, is that the golf works for any number which has exactly two primes as its factors, as is certainly* the case for the numbers given in the RSA challenge.

      * For sufficiently high and practical values of certainty

      Update: here's a recursive version that does what you're looking for at 52 chars:
        
      sub f { my$n=my$p=pop;1while$n%--$p;$p>1?(f($n/$p),f($p)):$n }

         MeowChow                                   
                     s aamecha.s a..a\u$&owag.print