数论
欧几里得算法求最大公约数
import java.util.*;
class Main
{public static void main(String[] args){Scanner sc = new Scanner(System.in);int a=sc.nextInt();int b=sc.nextInt();System.out.print(gcd(a,b));}public static int gcd(int a,int b){return b!=0 ? gcd(b,a%b) : a;}
}
线性筛法求质数
import java.util.*;
class Main
{public static int N=1000000;public static int[] primes = new int[N]; //记录素数public static boolean[] st = new boolean[N]; //有没有被筛过public static int[] minp = new int[N]; //最小质因子public static void main(String[] args){Scanner sc = new Scanner(System.in);int n=sc.nextInt();get_primes(n);for(int i=0;i<=n;i++){if(primes[i]==0)break;System.out.print(primes[i]+" ");}}public static void get_primes(int n) //O(n){int cnt=0;for(int i=2;i<=n;i++){if(!st[i]){minp[i]=i;primes[cnt++]=i;}for(int j=0;primes[j]*i<=n;j++){st[primes[j]*i]=true;minp[primes[j]*i]=primes[j];if(i%primes[j]==0) break;}}}
}
约数个数与和
N = p 1 α 1 ⋅ p 2 α 2 ⋅ ⋅ ⋅ p k α k N=p_1^{\alpha_1}·p_2^{\alpha_2}···p_k^{\alpha_k} N=p1α1⋅p2α2⋅⋅⋅pkαk
约数个数: ( α 1 + 1 ) ( α 2 + 1 ) ⋅ ⋅ ⋅ ( α k + 1 ) (\alpha_1+1)(\alpha_2+1)···(\alpha_k+1) (α1+1)(α2+1)⋅⋅⋅(αk+1)
约数之和: ( 1 + p 1 + p 1 2 + ⋅ ⋅ ⋅ + p 1 α 1 ) ( 1 + p 2 + p 2 2 + ⋅ ⋅ ⋅ + p 2 α 2 ) ⋅ ⋅ ⋅ ( 1 + p k + p k 2 + ⋅ ⋅ ⋅ + p k α k ) (1+p_1+p_1^2+···+p_1^{\alpha_1})(1+p_2+p_2^2+···+p_2^{\alpha_2})···(1+p_k+p_k^2+···+p_k^{\alpha_k}) (1+p1+p12+⋅⋅⋅+p1α1)(1+p2+p22+⋅⋅⋅+p2α2)⋅⋅⋅(1+pk+pk2+⋅⋅⋅+pkαk)
裴蜀定理
a x + b y = g c d ( a , b ) ax+by=gcd(a,b) ax+by=gcd(a,b)
扩展欧几里得算法
import java.util.*;
class Int //代替指针
{int v;public Int(){}public Int(int v){this.v=v;}
}
class Main
{public static void main(String[] args){Scanner sc = new Scanner(System.in);int a=sc.nextInt();int b=sc.nextInt();Int x = new Int();Int y = new Int();int d=exgcd(a,b,x,y);System.out.printf("%d * %d + %d * %d = %d",a,x.v,b,y.v,d);}public static int exgcd(int a,int b,Int x,Int y){if(b==0){x.v=1;y.v=0;return a;}int d=exgcd(b,a%b,y,x);y.v-=(a/b)*x.v;return d;}
}
其他数学知识
如果 a , b a,b a,b,均是正整数且互质,那么由 a x + b y ( x ≥ 0 , y ≥ 0 ) ax+by(x≥0,y≥0) ax+by(x≥0,y≥0) 不能凑出的最大数是 a b − a − b . ab−a−b. ab−a−b.
也即 a a a 与 b b b 的最大公因数 ( a , b ) = 1 (a,b)=1 (a,b)=1,最大不能凑出来的数是 ( a − 1 ) ( b − 1 ) − 1 (a-1)(b-1)-1 (a−1)(b−1)−1