原文: https://www.programiz.com/java-programming/examples/gcd-hcf-recursion
该程序采用两个正整数,并使用递归计算 GCD。
访问此页面以了解如何使用循环来计算 GCD。
public class GCD {
public static void main(String[] args) {
int n1 = 366, n2 = 60;
int hcf = hcf(n1, n2);
System.out.printf("GCD 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;
}
}运行该程序时,输出为:
GCD 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 | - |