From 338524a725797fb46984f5d98db6df8556dd4f17 Mon Sep 17 00:00:00 2001 From: Randy Lauen Date: Wed, 28 Aug 2019 20:37:10 -0500 Subject: perl5 solution for task2 --- challenge-023/randy-lauen/perl5/ch-2.pl | 50 +++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 challenge-023/randy-lauen/perl5/ch-2.pl 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; +} + -- cgit