1、窮舉法java
/** 窮舉法 */ public int gcdExhaustion(int firstNumber, int secondNumber) { int n1 = Math.abs(firstNumber); int n2 = Math.abs(secondNumber); int gcd = 1; for (int i = 1; i <= n1 && i <= n2; i++) { if (0 == n1 % i && 0 == n2 % i) gcd = i; } return gcd; }
2、歐幾里德算法算法
定義:假設x%y=r,則x與y的最大公約數等於y與r的最大公約數code
/** 歐幾里德算法 (迭代)*/ public int gcdEuclid(int firstNumber, int secondNumber) { int n1 = Math.abs(firstNumber); int n2 = Math.abs(secondNumber); int r = n1 % n2; while(0 != r) { n1 = n2; n2 = r; r = n1 % n2; } return n2; } /** 歐幾里德算法(遞歸) */ public int gcdEuclid2(int firstNumber, int secondNumber) { int n1 = Math.abs(firstNumber); int n2 = Math.abs(secondNumber); int r = n1 % n2; if (0 == r) return n2; return gcdEuclid2(n2, r); }