diff options
| author | Randy Lauen <randy.lauen@gmail.com> | 2019-08-28 20:37:10 -0500 |
|---|---|---|
| committer | Randy Lauen <randy.lauen@gmail.com> | 2019-08-28 20:37:10 -0500 |
| commit | 338524a725797fb46984f5d98db6df8556dd4f17 (patch) | |
| tree | 36878f9a5fd663a2cd2ebcdf4e5434b621501bf7 | |
| parent | 0b6f3d1ba100c5b7c9d8048e76bb4682188e17ab (diff) | |
| download | perlweeklychallenge-club-338524a725797fb46984f5d98db6df8556dd4f17.tar.gz perlweeklychallenge-club-338524a725797fb46984f5d98db6df8556dd4f17.tar.bz2 perlweeklychallenge-club-338524a725797fb46984f5d98db6df8556dd4f17.zip | |
perl5 solution for task2
| -rw-r--r-- | challenge-023/randy-lauen/perl5/ch-2.pl | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/challenge-023/randy-lauen/perl5/ch-2.pl b/challenge-023/randy-lauen/perl5/ch-2.pl new file mode 100644 index 0000000000..45aae0214e --- /dev/null +++ b/challenge-023/randy-lauen/perl5/ch-2.pl @@ -0,0 +1,50 @@ +#!/usr/bin/env perl + +=head1 SYNOPSIS + +Task: +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. + +Usage: + $ perl ch-2.pl 228 + +Notes: +I used the algorithm described here: https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/ + +=cut + +use strict; +use warnings; +use feature 'say'; + +my $num = $ARGV[0] // ''; +die "Must pass an integer > 0 as the first argument\n" unless $num && $num =~ /^\d+$/; + +say $num == 1 + ? "No prime factors for 1" + : join(', ', prime_factors( $num ) ) +; + +exit 0; + +sub prime_factors { + my $n = shift; + + my @factors; + while ( $n % 2 == 0 ) { + push @factors, 2; + $n /= 2; + } + for ( my $i = 3; $i <= sqrt($n); $i += 2 ) { + while ( $n % $i == 0 ) { + push @factors, $i; + $n /= $i; + } + } + push @factors, $n if $n > 2; + + return @factors; +} + |
