Java Program to Find GCD of Two Numbers using While loop
ADVERTISEMENTS
Java program to find GCD of two numbers using while loop. In this article, you will learn how to find gcd of two numbers in java language using while loop.
What is GCD Number?
The GCD is the largest integer number of two positive integer numbers that can exactly divide both numbers without remaining a remainder.
Java Program to Find GCD of Two Numbers using While loop
// Java Program to Find GCD 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;
// p & q - To store the two positive numbers
System.out.println ("-----Enter the two positive integer numbers-----");
p = in.nextInt();
q = in.nextInt();
while (p != q) {
if (p > q) {
p -= q;
} else {
q -= p;
}
}
System.out.println ("\nThe GCD number is: " + p);
}
}
Output
-----Enter the two positive integer numbers-----
180
90
The GCD number is: 90
Java Program to Find GCD of Two Numbers using For loop
// Java Program to Find GCD 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;
// p & q - To store the two positive numbers
// g - To store the GCD number
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;
}
}
System.out.println ("\nThe GCD number if " + p + " & " + q + " is: " + g);
}
}
Output
-----Enter the two positive integer numbers-----
180
90
The GCD number if 180 & 90 is: 90