在该程序中,您将学习使用Java中的递归函数查找GCD(最大公约数)或HCF。
该程序采用两个正整数,并使用递归计算GCD。
访问此页面以了解如何使用循环来计算 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;
}
}运行该程序时,输出为:
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 | -- |