intGCD(int x,int y){int t;while(y >0){
t = x % y;
x = y;
y = t;}return x;}
2. Prime素数判断
bool is_prime(int u){if(u ==0|| u ==1)return false;if(u ==2)return true;if(u%2==0)return false;for(int i=3; i <=sqrt(u);i+=2)if(u%i==0)return false;return true;}
3. Sieve Prime素数筛法
constint M =1000;// M : size
bool mark[M];// true : prime numbervoidsieve_prime(){memset(mark, true,sizeof(mark));
mark[0]= mark[1]= false;for(int i=2; i <=sqrt(M);i++){if(mark[i]){for(int j=i*i; j < M ;j+=i)
mark[j]= false;}}}
4. Module Inverse模逆元
// ax ≡ 1 (mod n)intInv(int a,int n){int d, x, y;
d =extended_euclid(a, n, x, y);if(d ==1)return(x%n + n)% n;elsereturn-1;// no solution}
5. Extended Euclid扩展欧几里德算法
//如果GCD(a,b) = d, 则存在x, y, 使d = ax + by// extended_euclid(a, b) = ax + byintextended_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;}
6. Modular Linear Equation模线性方程(同余方程)
//如果GCD(a, b)不能整除c, 则ax + by = c 没有整数解// ax ≡ b (mod n) n > 0//上式等价于二元一次方程ax – ny = bvoidmodular_linear_equation(int a,int b,int n){int d, x, y, x0;
d =extended_euclid(a, n, x, y);if( b%d ==0){
x0 =( x*(b/d))% n;// x0 : basic solutionint ans = n;for(int i=0; i < d ;i++){
ans =( x0 + i*(n/d))% n;
cout << ans << endl;}}else cout <<"no solution"<< endl;}
7. Chinese Remainder Theorem中国余数定理
// x ≡ b[i] (mod w[i]), i∈[1, len-1]// 前提条件w[i] > 0, 且w[]中任意两个数互质intchinese_remainder(int b[],int w[],int len){int i, d, x, y, m, n;
x =0; n =1;for(i=0; i < len ;i++) n *= w[i];for(i=0; i < len ;i++){
m = n / w[i];
d =extended_euclid(w[i], m, x, y);
x =(x + y*m*b[i])% n;}return(n + x%n)% n;}
数论算法1. Greatest Common Divisor最大公约数int GCD(int x, int y){ int t; while(y > 0) { t = x % y; x = y; y = t; } return x;}2. Prime素数判断bool is_prime(int u){ if(u == 0 || u == 1) return false;