JAVA Program to find LCM of two numbers using simplest algorithm
Add caption |
LCM stands for Least Common Multiple
But.....what is a "Multiple" ?
We get a multiple of a number when we multiply it by another number. Such as multiplying by 1, 2, 3, 4, 5, etc, but not zero. Just like the multiplication table.
Here are some examples:
The multiples of 2 are:2 4 6 8 10 12 14 16 18 20 22 ……
The multiples of 3 are:3 6 9 12 15 18 21……
Notice that 6 and 12 appear in both lists?
So, the common multiples of 2 and 3 are: 6, 12, (and 18, 24, etc ... too)
So What is the "Least Common Multiple" ?
It is simply the smallest of the common multiples.
In our previous example, the smallest of the common multiples is 6 ...........
so the Least Common Multiple of 2 and 3 is 6.
Join Us
For those who prefer reading on mobile, we have Telegram channel and WhatsApp group that will allow you to receive updates, announcements, and links to our stories straight to your mobile device..
Steps to be followed for finding LCM
- Input two number from user, let it be num1 and num2.
- Now create a loop which starts from i=1 and ends at i<=(num1 X num2)
- Inside Loop if i%num1==0 && i%num2==0 .
- Print i and apply break statement.
Sounds Good? Let's get started
CODE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /* * Author: TheSchoolProgrammer * www.theschoolprogrammer.com * Question:Write a program to accept two numbers and print their LCM */ import java.util.*; public class LCM { public static void main() { Scanner sc=new Scanner(System.in); System.out.println("ENTER 1st NUMBER"); int num1=sc.nextInt(); System.out.println("ENTER 2nd NUMBER"); int num2=sc.nextInt(); int i; for(i=1;i<=num1*num2;i++) { if(i%num1==0 && i%num2==0) { System.out.print("LCM : "+i); break; } } } } |
Example 1 Input: ENTER 1st NUMBER 48 ENTER 2nd NUMBER 36 Output: LCM: 144
Example 2 Input: ENTER 1st NUMBER 12 ENTER 2nd NUMBER 6 Output: LCM: 12
Found this useful? Share with your friends. Share
👍👍
ReplyDelete