Methods
Java Program to Find GCD Using Recursion
A Java program to find the Greatest Common Divisor (GCD) of two numbers using recursion.
Problem Description
Write a Java program to find the GCD (HCF) of two numbers using recursion.
Code
public class GCDRecursion {
public static void main(String[] args) {
int n1 = 366, n2 = 60;
int hcf = hcf(n1, n2);
System.out.printf("G.C.D of %d and %d is %d.", n1, n2, hcf);
}
public static int hcf(int n1, int n2) {
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
}Output
G.C.D of 366 and 60 is 6.Explanation
- Euclidean Algorithm: Efficient method for computing GCD.
- Recursion:
hcf(n2, n1 % n2)untiln2becomes 0.
