在該程序中,您將學(xué)習(xí)使用Java中的遞歸函數(shù)查找GCD(最大公約數(shù))或HCF。
該程序采用兩個(gè)正整數(shù),并使用遞歸計(jì)算GCD。
訪問(wèn)此頁(yè)面以了解如何使用循環(huán)來(lái)計(jì)算 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; } }
運(yùn)行該程序時(shí),輸出為:
G.C.D of 366 and 60 is 6.
在上面的程序中,遞歸函數(shù)被調(diào)用直到n2為0。最后,n1的值是給定兩個(gè)數(shù)字的GCD或HCF。
No. | 遞歸調(diào)用 | n1 | n2 | n1 % n2 |
---|---|---|---|---|
1 | hcf(366,60) | 366 | 60 | 6 |
2 | hcf(60,6) | 60 | 6 | 0 |
最后 | hcf(6,0) | 6 | 0 | -- |