LCM of two numbers | MATLAB Tutorial
by SAURAB S
- It is the abbreviation of least common multiple.
- It is the lowest common multiple of two or more numbers.
For Example – LCM of
- 2 and 4 is 4
This is because 2×2 is 4 and 4×1 is 4 hence both have same value at 4.Similarly,
- 3 and 11 is 33
This is because 3×11 and 11×3 is 33 and this is the least common multiple both the numbers have and there are no other numbers that are common before 33.
- 7 and 22 is 154.
- 4 and 6 is 12.
- 3 and 6 is 6.
A short procedure for finding the Least Common Multiple of two numbers is by multiplying the two numbers and then dividing it by the gcd of the two numbers.
LCM = (number1 * number2)/HCF(number1,number2)
x1=input('Enter number 1 :'); x2=input('Enter number 2 :'); a=max(x1,x2); for i=1:a if mod(x1,i)==0 && mod(x2,i)==0 GCD=i; end end LCM=(x1*x2)/GCD fprintf('LCM of %d and %d is %d',x1,x2,LCM) fprintf('\n')
- In particular user finds HCF of the two numbers and then finally divides the product of number 1 and number 2.
- Here two numbers are entered by us in MATLAB. Then these two numbers are stored in variables. Let the two variables be x1 and x2.
- Then a for loop is used where a variable ‘i’ tends from 0 to max(x1,x2).
- On one hand inside this for loop, the numbers x1 and x2 are divided by ‘i’ in each loop. At the same time whenever x1 and x2 are exactly divisible by ‘i’ then the value of gcd is set to ‘i’.
- After this, when the for loop has finished being executed, the gcd variable will have the HCF of two numbers.
- Now the procedure is to take the product of the two numbers.
- And then in the last stage, we divide it by the HCF.
- Thus, LCM=(number1*number2)/HCF
Thus, here are some example outputs for different inputs