From 19dfa2ca7999dd30102a6b658b6ee407a559bb6e Mon Sep 17 00:00:00 2001 From: Guillermo Ramos Date: Fri, 30 Aug 2019 15:02:54 +0200 Subject: [023#2] --- 023/ch2.pl | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100755 023/ch2.pl (limited to '023') 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; + +my $n = my $number = shift or die "Usage: $0 "; + +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!"; -- cgit v1.2.3