English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)

Java Reader/Writer

Java Other Topics

Java program uses recursion to find the greatest common divisor

Comprehensive List of Java Examples

In this program, you will learn to use recursive functions in Java to find the GCD (Greatest Common Divisor) or HCF.

This program takes two positive integers and calculates using recursionGCD.

Visit this page to learn howCalculate using a loop GCD.

Example: Using recursion to find the GCD of two numbers

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

When the program is run, the output is:

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

In the above program, the recursive function is called until n2is 0. Finally, n1The value is the Greatest Common Divisor (GCD) or Highest Common Factor (HCF) of the given two numbers.

Execution Steps
No.Recursive Calln1n2n1 % n2
1hcf(366,60)366606
2hcf(60,6)6060
Lasthcf(6,0)60--

Comprehensive List of Java Examples