#!env perl # # factor.pl # # Print the list of prime factors for Number # # 20130206 Can't find a copy on my hard drive, so making it again use strict; use warnings; my \$num = shift or die "Expected number to factor!"; print "\$num: ", join(", ", factors(\$num)), "\n"; sub factors { my \$val=shift; return unless \$val; my @primes = (1); if (\$val < 0) { unshift @primes, -1; \$val = -\$val; } while (\$val % 2 == 0) { push @primes, 2; \$val = \$val/2; } my \$fac=3; while (\$fac*\$fac <= \$val) { while (\$val % \$fac == 0) { push @primes, \$fac; \$val = \$val / \$fac; } \$fac += 2; } push @primes, \$val if \$val > 1; return @primes; } ##```## sub do_tests { use Test::More; use Data::Dump 'pp'; my @test_cases = ( [ 0, [] ], [ 1, [1] ], [ 2, [1, 2] ], [ 3, [1, 3] ], [ 4, [1, 2, 2] ], [ -72, [-1, 1, 2, 2, 2, 3, 3] ], ); for my \$case (@test_cases) { my @f = factors(\$case->[0]); # Uncomment for debugging #print "\$case->[0], exp: (", join(",",@{\$case->[1]}), "), got(", join(",",@f),")\n"; is_deeply([@f], \$case->[1]); } done_testing(); } ##``````## if (\$num eq "-test") { do_tests(); } else { print "\$num: ", join(", ", factors(\$num)), "\n"; } ##``````## \$ perl pm_1224882.pl 1234 1234: 1, 2, 617 Roboticus@Waubli ~ \$ perl pm_1224882.pl -test ok 1 ok 2 ok 3 ok 4 ok 5 ok 6 1..6 ```