该程序采用两个正整数并使用递归计算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 | 
| hcf(366, 60) | 366 | 60 | 6 | 
| hcf(60, 6) | 60 | 6 | 0 | 
| hcf(6, 0) | 6 | 0 | - | 

 
    