English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
En este programa, aprenderá a usar funciones recursivas en Java para encontrar el MCD (máximo común divisor) o HCF
Este programa toma dos enteros positivos y los calcula usando recursiónMCD.
Acceda a esta página para saber cómoUso de bucles para calcular MCD.
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; } }
运行该程序时,输出为:
G.C.D of 366 and 60 is 6.
在上面的程序中,递归函数被调用直到n2为0。最后,n1的值是给定两个数字的GCD或HCF。
No. | 递归调用 | n1 | n2 | n1 % n2 |
---|---|---|---|---|
1 | hcf(366,60) | 366 | 60 | 6 |
2 | hcf(60,6) | 60 | 6 | 0 |
最后 | hcf(6,0) | 6 | 0 | -- |