基础数论(逆元,中国剩余定理)(模板~)

一  逆元

1.逆元的含义:模n意义下,1个数a如果有逆元x,那么除以a相当于乘以x。

2 方法

(1)费马小定理

在模为素数p的情况下,有费马小定理
a^(p-1)=1(mod p)
那么a^(p-2)=1/a(mod p)

(2)扩展欧几里得算法        a∗x+b∗y=gcd(a,b)

ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(b==0)
    {
        x=1;
        y=0;
        return a;
    }
    ll d=exgcd(b,a%b,x,y);
    ll t=x;
    x=y;
    y=t-a/b*y;
    return d;
}

ll inv(ll a,ll n)//模n下a的逆,如果不存在返回-1
{
    ll d,x,y;
    d=exgcd(a,n,x,y);
    return d==1?(x+n)%n:-1;
}

二:中国剩余定理:
1.满足两两互质关系

LL china(int n, LL *a, LL *m)
{
    LL M = 1, ret = 0;
    for(int i = 0; i < n; i ++) M *= m[i];
    for(int i = 0; i < n; i ++)
    {
        LL w = M / m[i];
        ret = (ret + w * inv(w, m[i]) * a[i]) % M;
    }
    return (ret + M) % M;
}

2  不满足两两互质关系

typedef long long LL;
typedef pair<LL, LL> PLL;
PLL linear(LL A[], LL B[], LL M[], int n)  //求解A[i]x = B[i] (mod M[i]),总共n个线性方程组
{
    LL x = 0, m = 1;
    for(int i = 0; i < n; i ++)
    {
        LL a = A[i] * m, b = B[i] - A[i]*x, d = gcd(M[i], a);
        if(b % d != 0)  return PLL(0, -1);//答案不存在,返回-1
        LL t = b/d * inv(a/d, M[i]/d)%(M[i]/d);
        x = x + m*t;
        m *= M[i]/d;
    }
    x = (x % m + m ) % m;
    return PLL(x, m);//返回的x就是答案,m是最后的lcm值
}

附上一个题

一个正整数K,给出K Mod 一些质数的结果,求符合条件的最小的K。例如,K % 2 = 1, K % 3 = 2, K % 5 = 3。符合条件的最小的K = 23。

Input

第1行:1个数N表示后面输入的质数及模的数量。(2 <= N <= 10)
第2 - N + 1行,每行2个数P和M,中间用空格分隔,P是质数,M是K % P的结果。(2 <= P <= 100, 0 <= K < P)

Output

输出符合条件的最小的K。数据中所有K均小于10^9。

Sample Input

3
2 1
3 2
5 3

Sample Output

23
#include<iostream>
#include<queue>
using namespace std;
typedef long long ll;
ll exgcd(ll a, ll b, ll &x, ll &y) {
    ll d;
    if(b == 0) {x = 1; y = 0; return a;}
    d = exgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
ll china(ll b[], ll w[], ll len) {
    ll i, d, x, y, m, n, ret;
    ret = 0; n = 1;
    for(i=0; i < len ;i++) n *= w[i];
    for(i=0; i < len ;i++) {
        m = n / w[i];
        d = exgcd(w[i], m, x, y);
        ret = (ret + y*m*b[i]) % n;
    }
    return (n + ret%n) % n;
}

ll a[100],b[100];
int main()
{
	ll n;
	while(cin>>n)
	{
		for(ll i=0;i<n;i++)
		{
			cin>>b[i]>>a[i];
		}
		ll ans=china(a,b,n);
		cout<<ans<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zcy19990813/article/details/81128872