本程序接受两个正整数,并使用递归计算GCD。
访问此页面,了解如何使用循环来计算 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。
否。 | 递归调用 | n1 | n2 | n1 % n2 |
---|---|---|---|---|
1 | hcf(366, 60) | 366 | 60 | 6 |
2 | hcf(60, 6) | 60 | 6 | 0 |
最终 | hcf(6, 0) | 6 | 0 | - |