"血をもって書け。そうすればあなたは、血が精神だということを経験するだろう。"

素因数分解

Haskellhttp://d.hatena.ne.jp/satzz/20080421/1208746502のほぼ直訳

use strict;
use warnings;
print join ("\t", factors(600851475143));
sub factors {
  my ($target, $guess) = @_;
  $guess ||= 2;
  return ($target) if $guess * $guess > $target;
  #return (factors($guess), factors($target / $guess)) unless $target % $guess;
  #コメント欄で修正いただきました
  return ($guess, factors($target / $guess, $guess)) unless $target % $guess;
  return factors($target, $guess + 1);
}

もうちょい手続き型っぽく

use strict;
use warnings;
print join ("\t", factors(600851475143));
sub factors {
  my @targets = @_;
  my @ret;
  while (my $this_target = shift @targets) {
    my $flag = 1;
    for my $guess (2 .. sqrt($this_target)) {
      unless ($this_target % $guess) {
        @targets = (@targets, $guess, $this_target / $guess);
        undef $flag;
        last;
      }
    }
    @ret = (@ret, $this_target) if $flag;
  }
  @ret;
}