[数论专题]

时间:2020-05-29
本文章向大家介绍[数论专题],主要包括[数论专题]使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一:素数

 1 int prime[N],p[N],tot;
 2 void init()
 3 {
 4     for(int i=2;i<N;i++)    prime[i]=1;
 5     for(int i=2;i<N;i++)
 6     {
 7         if(prime[i]==1) p[++tot]=i;
 8         for(int j=1;j<=tot;j++)
 9         {
10             prime[i*p[j]]=0;
11             if(i%p[j]==0)   break;
12         }
13     }
14 }
View Code

二:快速幂

1 LL pow_mod(LL a, LL b, LL p){//a的b次方求余p
2     LL ret = 1;
3     while(b){
4         if(b & 1) ret = (ret * a) % p;
5         a = (a * a) % p;
6         b >>= 1;
7     }
8     return ret;
9 }
View Code

快速乘

1 LL mul(LL a, LL b, LL p){//快速乘,计算a*b%p
2     LL ret = 0;
3     while(b){
4         if(b & 1) ret = (ret + a) % p;
5         a = (a + a) % p;
6         b >>= 1;
7     }
8     return ret;
9 }
View Code

三:gcd和lcm

lcm=a/gcd*b;

1 LL gcd(LL a, LL b){
2     if(b == 0) return a;
3     else return gcd(b, a%b);
4 }
5 
6 LL gcd(LL a, LL b){
7     return b ? gcd(b, a%b) : a;
8 }
9 //两种都可以
gcd

gcd(ka, kb) = k * gcd(a, b)

lcm(ka, kb) = k * lcm(a, b)

lcm(S/a, S/b) = S/gcd(a, b)

四:扩展欧几里得算法

已知 a,b 求 一组解 x,y 满足 ax+by = gcd(a, b) 这个公式

 1  void ex_gcd(LL a, LL b, LL &d, LL &x, LL &y)
 2 {
 3     if(!b)
 4         {d = a; x = 1; y = 0;}
 5      else
 6     {
 7         ex_gcd(b, a%b, d, y, x); 
 8         y -= x*(a/b);
 9     }    
10 }
View Code

原文地址:https://www.cnblogs.com/Kaike/p/12987450.html