编程之美:最大公约数问题
2014-03-14 21:26
169 查看
/* 最大公约数 */ #include <stdio.h> /* 方法1:辗转相除 缺点:对于大整数,取模运算开销大 */ int gcd(int x,int y){ return y==0?x:gcd(y,x%y); } /* 方法2: 缺点:迭代次数过多 */ int gcd2(int x,int y){ if(x<y) return gcd2(y,x); return y==0?x:gcd2(x-y,y); } /* 方法3: 1、如果y=k*y1,x=k*x1,那么有f(y,x)=k*f(y1,x1) 2、如果x=p*x1,且y%p!=0,假设p为素数,那么有f(x,y)=f(p*x1,y)=f(x1,y) 取p=2 若x,y为偶数,f(x,y)=2*f(x>>1,y>>1) 若x为偶数,y为奇数,f(x,y)=f(x>>1,y) 若x为奇数,y为偶数,f(x,y)=f(x,y>>1) 若x,y均为奇数,f(x,y)=f(x,x-y) */ int gcd3(int x,int y){ if(x<y) return gcd(y,x); if(y==0) return x; else{ if(!(x&1)){ if(!(y&1)) return gcd3(x>>1,y>>1)<<1; return gcd3(x>>1,y); } else{ if(!(y&1)) return gcd3(x,y>>1); return gcd(y,x-y); } } } int main(){ int a=12,b=8; printf("%d\n%d\n%d\n",gcd(a,b),gcd2(a,b),gcd3(a,b)); return 0; }
相关文章推荐
- 读书笔记之编程之美 – 2.7 最大公约数问题
- 编程之美 2.7 最大公约数 扩展问题之逆转一个整数的二进制表示
- 编程之美--2.7 最大公约数问题
- 【编程之美】2.7最大公约数问题
- 编程之美___最大公约数问题
- 编程之美-最大公约数问题方法整理
- 重新开始战斗13-编程之美-最大公约数问题
- 编程之美----最大公约数问题
- 编程之美_007最大公约数问题
- 编程之美---最大公约数问题
- 编程之美-2.7-最大公约数问题
- 编程之美-2.7、最大公约数问题
- 编程之美 set 3 最大公约数问题
- 编程之美--最大公约数问题--递归和非递归
- 编程之美-2.7最大公约数问题java解法
- C++基础编程 最大公约数问题
- 编程之美 -- 2.7 最大公约数问题
- 编程之美--最大公约数问题
- [编程之美] PSet2.7 最大公约数问题
- 每日一题(75) - 最大公约数问题