Java Program to Find G.C.D Using Recursion

In this program, you’ll learn to find the GCD (Greatest Common Divisor) or HCF using a recursive function in Java.

This program takes two positive integers and calculates GCD using recursion.

Visit this page to learn how you can calculate the GCD using loops.

Example: GCD of Two Numbers using Recursion

public class GCD {

    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);
            return n1;


G.C.D of 366 and 60 is 6.

In the above program, the recursive function is called until n2 is 0. In the end, the value of n1 is the GCD or HCF of the given two numbers.

No.Recursive calln1n2n1 % n2
1hcf(366, 60)366606
2hcf(60, 6)6060
Finalhcf(6, 0)60

Leave a Reply