L.C.M. of a Set of Numbers in Java - Maths Programming for Kids
What is LCM? | Maths Explanation for Java 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 Java.
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 Java
We shall follow the steps below in writing our Java 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 Java class file; File, New File.
Call it findLCM.
Type out the adjoining Java code for Lowest Common Multiple (L.C.M.)
Note: You can comment out the Java code for the main class
from the previous lesson if you have been following.
So! Java Fun Practice Exercise - Find LCM
As a fun practice exercise, feel free to try out your own numbers,
and see how the Java code finds the LCM of those numbers.
privatefinal Integer[] set_of_numbers; privatefinal Integer[] arg_copy; // Java passes arrays by reference; make a copy. private final List<Integer> all_factors = new ArrayList<>(); // factors common to our set_of_numbers
private intindex; // index into array common_factors private booleanstate_check; // variable to keep state private intcalc_result;
publicLCM(List<Integer> group) {
set_of_numbers = new Integer[group.size()];
arg_copy = new Integer[group.size()]; index = 0;
//iterate through and retrieve members for (int number : group) {
set_of_numbers[index] = number; index++;
}
/**
* Our function checks 'set_of_numbers'; If it finds a factor common to all
* for it, it records this factor; then divides 'set_of_numbers' by the
* common factor found and makes this the new 'set_of_numbers'. It continues
* recursively until all common factors are found.
*/ private intfindLCMFactors() {
System.arraycopy(set_of_numbers, 0, arg_copy, 0, set_of_numbers.length);
Arrays.sort(arg_copy, Collections.reverseOrder());
public static void main(String[] args) {
System.out.println("Welcome to our demonstration sequels");
System.out.println("Hope you enjoy (and follow) the lessons.");
System.out.println("");
/*
* Find LCM.
*/
String render_result = "The LCM of ";
LCM lcm;
List<Integer> group;
group = new ArrayList<>();
group.add(40);
group.add(50);
group.add(60);
for (int number : group) {
render_result += number + "; ";
}
render_result += "is: ";
lcm = new LCM(group);
System.out.println(render_result + lcm.getLCM());
}
}