复习2-数论模板
1.求最大公约数
#include<cstdio> using namespace std; int x,y; int gcd(int a,int b){ return b == 0 ? a : gcd(b,a%b); } int main(){ scanf("%d%d",&x,&y); printf("%d",gcd(x,y)); return 0; }
2.扩展欧几里得
int exgcd(int a,int b,int &x,int &y){ if(b == 0){ x = 1,y = 0; return a; } int r = exgcd(b,a%b,x,y); int t = x; x = y; y = t - a/b*y; return r; }
3.线性筛素数
void prime(){ for(int i = 0;i <= n;i++) is_prime[i] = 1; is_prime[0] = 0;is_prime[1] = 0; for(int i = 2;i <= n;i++){ if(is_prime[i]){ prime[tot] = i; for(int j = 2 * i;j <= n;j += i) is_prime[j] = 0; tot++; } } }
void prime(){ for(int i = 2;i <= n;i++){ if(!vis[i])p[++cnt] = i; for(int j = 1;j <= cnt&&i*p[j] <= n;j++){ vis[i*p[j]] = 1; if(i%p[j] == 0)break; } } }