Java program to find gcd of two numbers
To find the greatest common divisor (gcd) of two numbers in Java, we can use the Euclidean algorithm. The algorithm is based on the principle that the gcd of two numbers does not change if the larger number is replaced by its difference with the smaller number.
Here's a Java program that implements the Euclidean algorithm to find the gcd of two numbers:
import java.util.Scanner; public class GCD { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the first number: "); int num1 = sc.nextInt(); System.out.print("Enter the second number: "); int num2 = sc.nextInt(); int gcd = findGCD(num1, num2); System.out.println("The gcd of " + num1 + " and " + num2 + " is " + gcd); } public static int findGCD(int num1, int num2) { while (num2 != 0) { int temp = num2; num2 = num1 % num2; num1 = temp; } return num1; } }
In this program, we first take two numbers as input from the user using the Scanner
class. We then call the findGCD
function with these two numbers to compute their gcd. The findGCD
function implements the Euclidean algorithm using a while loop. We start with the two numbers as num1
and num2
, and in each iteration of the loop, we replace the larger number with its difference with the smaller number. We continue this process until num2
becomes 0, at which point we have found the gcd, which is stored in num1
.
The program then prints the gcd of the two numbers.