你可以看BigInteger类是怎么计算大数的 /** * Calculate GCD of this and b. This and b are changed by the computation. */ MutableBigInteger hybridGCD(MutableBigInteger b) { // Use Euclid's algorithm until the numbers are approximately the // same length, then use the binary GCD algorithm to find the GCD. MutableBigInteger a = this; MutableBigInteger q = new MutableBigInteger(); while (b.intLen != 0) { if (Math.abs(a.intLen - b.intLen) < 2) return a.binaryGCD(b); MutableBigInteger r = a.divide(b, q); a = b; b = r; } return a; } // Use Euclid's algorithm until the numbers are approximately the // same length, then use the binary GCD algorithm to find the GCD. 具体去看源代码吧
* Calculate GCD of this and b. This and b are changed by the computation.
*/
MutableBigInteger hybridGCD(MutableBigInteger b) {
// Use Euclid's algorithm until the numbers are approximately the
// same length, then use the binary GCD algorithm to find the GCD.
MutableBigInteger a = this;
MutableBigInteger q = new MutableBigInteger(); while (b.intLen != 0) {
if (Math.abs(a.intLen - b.intLen) < 2)
return a.binaryGCD(b); MutableBigInteger r = a.divide(b, q);
a = b;
b = r;
}
return a;
}
// Use Euclid's algorithm until the numbers are approximately the
// same length, then use the binary GCD algorithm to find the GCD.
具体去看源代码吧
为了便于说明算法,我这里将a,b假设成比较小的数,超大数一样
a="342";
b="23"
首先判断a的第一个字母是否大于b的第一个字母,这里大于(不大于的情况,稍做处理即可)
得到3>2,条件为真,接下来可以取得一个数t,使得t*2 > 3,很显然这里取得t=2
这样我们就可以得到另外一个数n = t-1,然后将b里的每个字符乘以n就得到一个数c
再用左对齐的方式使用a-c就可以得到一个数,将这个数赋值成a,递归上面的方式,就可以了
简单列举下过程如下:
a="342"
b="23"
根据上面的思想,得到 34 - 23*1 =11 (这里n=1) 所以第一趟递归结束后得到
a="112"
b="23"
第二趟 112-23*4 = 20 (n=4) 结束后
a=20
b=23
由于b已经大于a,退出递归,从而我们也得到了字符"342" 除以 "23" 商等于14(n连接起来的数)
余数是20,这样就完成了字符串的除法
然后将赋值:a=34 b=20 继续调用上面的方法,就可以求出最大公约数了}