English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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.
No. | Recursive Call | n1 | n2 | n1 % n2 |
---|---|---|---|---|
1 | hcf(366,60) | 366 | 60 | 6 |
2 | hcf(60,6) | 60 | 6 | 0 |
Last | hcf(6,0) | 6 | 0 | -- |