L.C.M. of a Set of Numbers in Perl - Maths Programming for Kids
What is LCM? | Maths Explanation for Perl Kids
Akin to finding H.C.F., L.C.M. is commonly found by repeated factorization.
Only this time, the factors do not have to be common amongst the set of numbers.
If we have the set of numbers 8, 12 and
18 for example, their L.C.M. is found thus:
Figure: Math steps on how to find L.C.M. using prime factorization method in Perl.
Hence, L.C.M. of 8, 12 and 18 = 2 X 2 X 2 x 3 x 3 = 72
Step-by-Step Guide to L.C.M. by Factorisation in Perl
We shall follow the steps below in writing our Perl LCM code.
Step 1:
Do a numerical reverse sort on the (resulting) set so its first member
is the largest in the set.
Step 2:
Starting with 2, iteratively check through the set
of numbers for individual factors.
Step 3:
For each individual factor, divide affected member(s) of the number
set by the factor.
Step 4:
Repeat the above steps recursively until there are no more
individual factors.
Create a new Perl class file; File, New File.
Call it FindLCM.pm
Type out the adjoining Perl code for finding Lowest Common Multiple (L.C.M.)
Note: You can comment out the Perl code for the main class
from the previous lesson if you have been following.
So! Perl Fun Practice Exercise - Find LCM
As a fun practice exercise, feel free to try out your own numbers,
and see how the Perl code finds the LCM of those numbers.
Perl Code for Find LCM - Module File.
package LCM;
BEGIN { require Exporter;
# for the sake of standard our$VERSION = 2016.12;
# Inherit from exporter to export functions and variables our@ISA = qw(Exporter);
# Functions and variables to be exported by default our@EXPORT_OK = qw(getLCM);
}
use warnings; use strict;
my ($index, $state_check, $calc_result); my (@set_of_numbers, @arg_copy, @all_factors);
# simulate an object construct # takes one arguments -- besides its name; # array reference of values whose LCM is sought sub new { no warnings "all";