English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à utiliser la fonction récursive en Java pour trouver le PPCM (le plus grand commun diviseur) ou HCF.
Ce programme utilise deux entiers positifs et calcule le PPCM de manière récursivePPCM。
Accédez à cette page pour comprendre commentCalculer en utilisant une boucle PPCM。
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 running the program, 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 |
Finally | hcf(6,0) | 6 | 0 | -- |