Algorithm,Number Theory,GCD
2013-07-24 13:08
190 查看
#ifndef GCD_H #define GCD_H #include <cstdlib> #include <cmath> #include <algorithm> /***************************************************/ // 最大公约数_ int GCD(int x, int y) { int t; while(y > 0) { t = x % y; x = y; y = t; } return x; } /***************************************************/ // 快速gcd_ int kgcd(int a, int b) { if (a == 0) return b; if (b == 0) return a; // a,b都是偶数 if (!(a&1) && !(b&1)) return kgcd(a>>1, b>>1) << 1; // a 奇 b 偶 else if (!(b&1)) return kgcd(a, b>>1); else if (!(a&1)) return kgcd(b, a>>1); else return kgcd(abs(a - b), std::min(a, b)); } /***************************************************/ // a,n 互质,a 对 n 逆元 // ax ≡ 1 (mod n) int Inv(int a, int n) { int d, x, y; d = extended_euclid(a, n, x, y);// d = ax + ny if(d == 1) return (x%n + n) % n;// x可能为负数 else return -1; // no solution } /***************************************************/ //如果GCD(a,b) = d, 则存在x, y, 使d = ax + by // GCD(a, b) = ax + by // a,b的线性组合系数,存在x,y中,返回 GCD(a,b) // 递归式: a = bq + t // d = x'b + y't // 代入: d = x'b + y'(a - bq) // 得到 a系数 y', b系数 x' - qy' int extended_euclid(int a, int b, int &x, int &y) { int d; if(b == 0) {x = 1; y = 0; return a;} d = extended_euclid(b, a % b, y, x); y -= a / b * x; return d; } /***************************************************/ #endif // GCD_H
相关文章推荐
- Algorithm,Number Theory,Prime
- Binary GCD algorithm
- Euclid's GCD Algorithm——MIT Open Courseware(Computability)
- Leetcode: Water and Jug Problem && Summary: GCD求法(辗转相除法 or Euclidean algorithm)
- Euclidean gcd algorithm
- ACdream 1148 GCD SUM(数学:推理+数论:莫比乌斯函数)
- 多线程-GCD简记
- HDU 4630 gcd(线段树离线处理)
- hdu 4910 Problem about GCD
- GCD编程小记
- P2257 YY的GCD
- 【已解决】 java.security.KeyStoreException: java.security.NoSuchAlgorithmException
- iOS 多线程 GCD
- 51NOD 2026:Gcd and Lcm——题解
- GCD多线程编程
- GCD之dispatch queue深入浅出
- 洛谷P2257 YY的GCD 莫比乌斯反演
- IOS-线程操作之NSThread/NSOperation/GCD
- 2016 UESTC Training for Search Algorithm & String I - 谭爷剪花布条 KMP
- Algorithm---LCA(倍增算法)