diff options
author | Guillermo Ramos | 2019-08-30 15:02:54 +0200 |
---|---|---|
committer | Guillermo Ramos | 2019-08-30 15:02:54 +0200 |
commit | 19dfa2ca7999dd30102a6b658b6ee407a559bb6e (patch) | |
tree | f1684125b133b39fbf346bee8d765a66d0cea550 | |
parent | de3da0680396d9078a7197435d86b02e437ab72d (diff) | |
download | perlweekly-19dfa2ca7999dd30102a6b658b6ee407a559bb6e.tar.gz |
[023#2]
-rwxr-xr-x | 023/ch2.pl | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/023/ch2.pl b/023/ch2.pl new file mode 100755 index 0000000..fb3c699 --- /dev/null +++ b/023/ch2.pl @@ -0,0 +1,33 @@ +#!/usr/bin/env perl +# +# Create a script that prints Prime Decomposition of a given number. The prime +# decomposition of a number is defined as a list of prime numbers which when all +# multiplied together, are equal to that number. For example, the Prime +# decomposition of 228 is 2,2,3,19 as 228 = 2 * 2 * 3 * 19. +################################################################################ + +use strict; +use warnings; + +use List::Util qw<any>; + +my $n = my $number = shift or die "Usage: $0 <number>"; + +my @primes = (2); +my @factors; +while ($n != 1) { + my $lastp = $primes[-1]; + if ($n % $lastp == 0) { + push @factors, $lastp; + $n /= $lastp; + } else { + $lastp++ while any { $lastp % $_ == 0 } @primes; + push @primes, $lastp; + } +} + +print "$number = ", join("*", @factors), "\n"; + +# Quick test +$n *= $_ foreach (@factors); +$n == $number or die "Oops, something went wrong!"; |