jai*_*raj 2 c algorithm numbers
我想找到两个数字的GCD但不使用除法或运算符.一个显而易见的方法是编写自己的mod函数,如下所示:
enter code here
int mod(int a, int b)
{
while(a>b)
a-=b;
return a;
}
Run Code Online (Sandbox Code Playgroud)
然后在euclid算法中使用此函数.还有其他方法??
ami*_*mit 12
您可以预先使用基于减法的欧几里得算法版本:
function gcd(a, b)
if a = 0
return b
while b ? 0
if a > b
a := a ? b
else
b := b ? a
return a
Run Code Online (Sandbox Code Playgroud)
小智 7
您正在寻找的是二进制GCD算法:
public class BinaryGCD {
public static int gcd(int p, int q) {
if (q == 0) return p;
if (p == 0) return q;
// p and q even
if ((p & 1) == 0 && (q & 1) == 0) return gcd(p >> 1, q >> 1) << 1;
// p is even, q is odd
else if ((p & 1) == 0) return gcd(p >> 1, q);
// p is odd, q is even
else if ((q & 1) == 0) return gcd(p, q >> 1);
// p and q odd, p >= q
else if (p >= q) return gcd((p-q) >> 1, q);
// p and q odd, p < q
else return gcd(p, (q-p) >> 1);
}
public static void main(String[] args) {
int p = Integer.parseInt(args[0]);
int q = Integer.parseInt(args[1]);
System.out.println("gcd(" + p + ", " + q + ") = " + gcd(p, q));
}
}
Run Code Online (Sandbox Code Playgroud)
资料来源:http://en.wikipedia.org/wiki/Binary_GCD_algorithm