您的位置:首页 > 其它

辗转相除进化版--stein算法

2013-12-08 15:21 169 查看
#include <stdio.h>
#include <stdlib.h>

#define DECDATATYPE long

DECDATATYPE gcdcore(DECDATATYPE a,DECDATATYPE b) {
if (!a) return b;
if (!b) return a;

/* make a to odd number */
while (!(a & 0x1)) a=a>>1;

if (a<b) {
b=(b-a)>>1;
return gcdcore(b,a);
}else{
a=(a-b)>>1;
return gcdcore(a,b);
}
}
DECDATATYPE gcd(DECDATATYPE a,DECDATATYPE b) {
DECDATATYPE c=0;

/* make at least one of them from even to odd */
while (!(a&0x1) && !(b & 0x1)){
a=a>>1;
b=b>>1;
c++;
}

if (!(a&0x1)){
a=a>>1;
return gcdcore(a,b)<<c;
}else{
return gcdcore(b,a)<<c;
}
}

int main(int argc, char * args[]){
DECDATATYPE Num_A,Num_B;

if(argc < 3){
printf("Args error. Usage:$(proc_name) Num_A Num_B");
exit(0);
}

Num_A=atoi(args[1]);
Num_B=atoi(args[2]);

printf("Greatest Common Denominator between %ld and %ld is: %ld",Num_A,Num_B,gcd(Num_A,Num_B));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: