Java Program to Find LCM of Two Numbers using For loop
ADVERTISEMENTS
Java program to find LCM of two numbers using for loop. In this article, you will learn how to find lcm of two numbers in java language using for loop.
Java Program to Find LCM of Two Numbers using For loop
// Java Program to Find LCM of Two Numbers using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int p, q, i, g = 0, x;
// p & q - To store the two positive numbers
// x - To store the LCM number
// g - To store the GCD
System.out.println ("-----Enter the two positive integer numbers-----");
p = in.nextInt();
q = in.nextInt();
for (i = 1; i <= p && i <= q; ++i) {
if (p % i == 0 && q % i == 0) {
g = i;
}
}
x = (p * q) / g;
System.out.println ("\nThe LCM of two positive numbers " + p + " & " + q + " is " + x);
}
}
Output
-----Enter the two positive integer numbers-----
180
130
The LCM of the 180 and 130 numbers is 2340
Java Program to Find LCM of Two Numbers using While loop
// Java Program to Find LCM of Two Numbers using While loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int p, q, x;
// p & q - To store the two positive numbers
// x - To store the LCM number
System.out.println ("-----Enter the two positive integer numbers-----");
p = in.nextInt();
q = in.nextInt();
x = p > q ? p : q;
while (true) {
if (x % p == 0 && x % q == 0) {
System.out.println ("\nThe LCM of the " + p + " and " + q + " numbers is " + x);
break;
}
++x;
}
}
}
Output
-----Enter the two positive integer numbers-----
120
140
The LCM of two positive numbers 120 & 140 is 840