If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To calculate the Greatest Common Divisor (GCD) of two numbers in Java, you can use the Euclidean algorithm. The GCD of two integers is the largest positive integer that divides both of them without leaving a remainder. Here's a Java program to calculate the GCD of two given numbers:
javaCopy code
import java.util.Scanner;
public class GCDCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Calculate the GCD using the Euclidean algorithm
int gcd = calculateGCD(num1, num2);
System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);
scanner.close();
}
// Function to calculate GCD using the Euclidean algorithm
public static int calculateGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
Example output:
mathematicaCopy code
Enter the first number: 24
Enter the second number: 18
GCD of 24 and 18 is: 6
In the program above, we take the user input for the two numbers and store them in num1
and num2
variables. We then call the calculateGCD
function to calculate the GCD using the Euclidean algorithm. The calculateGCD
function uses a while
loop to repeatedly find the remainder of a
divided by b
and swap the values of a
and b
until b
becomes zero. At that point, the value of a
will be the GCD.
The calculateGCD
function is a separate method to demonstrate how to calculate the GCD using a function. It allows you to reuse the code in different parts of the program if needed.
The program then prints the GCD of the two numbers to the console.
Comments: 0