51nod1079(中国剩余定理)

1079 中国剩余定理

一个正整数K,给出K Mod 一些质数的结果,求符合条件的最小的K。例如,K % 2 = 1, K % 3 = 2, K % 5 = 3。符合条件的最小的K = 23。
输入
第1行:1个数N表示后面输入的质数及模的数量。(2 <= N <= 10)
第2 - N + 1行,每行2个数P和M,中间用空格分隔,P是质数,M是K % P的结果。(2 <= P <= 100, 0 <= K < P)
输出
输出符合条件的最小的K。数据中所有K均小于10^9。
输入样例
3
2 1
3 2
5 3
输出样例
23

C++代码:

#include<iostream>
using namespace std;
typedef long long ll;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(b==0)
    {
        x=1;
        y=0;
        return a;
    }
    else
    {
        ll r=exgcd(b,a%b,y,x);
        y-=x*(a/b);
        return r;
    }
}
ll CRT(ll a[],ll m[],ll n)
{
    ll M=1;
    for(int i=0;i<n;i++)
        M*=m[i];
    int ret=0;
    for(int i=0;i<n;i++)
    {
        ll x,y;
        ll tm=M/m[i];
        exgcd(tm,m[i],x,y);
        ret=(ret+tm*x*a[i])%M;
    }
    return (ret+M)%M;
}
int main()
{
    ll n,A[2333],B[2333];
    cin >> n;
    for(int i=0;i<n;i++)
    {
        cin >> B[i] >> A[i];
    }
    ll sum=CRT(A,B,n);
    cout << sum <<endl;
    return 0;
}

Java代码:

import java.util.*;

public class Main{
	static  long x,y,cnt,n;
	static long[]m = new long[500];
	static long[]a = new long[500];
	static long exgcd(long a,long b){
		
		if(b==0){
			x=1;
			y=0;
			return a;
		}
		long r=exgcd(b,a%b);
		long t=x;
		x=y;
		y=t-a/b*y;
		return r;
	}
	static long ctr(long[] a,long[] m,long n){
		long ans=0;
		long M=1;
		for(int i=0;i<n;i++){
			M*=m[i];
		}
		for(int i=0;i<n;i++){
			long Mi=M/m[i];
			long d=exgcd(Mi,m[i]);
			ans=(ans+a[i]*x*Mi)%M;
		}
		return (ans+M)%M;
	}
	
	public static void main(String[] args) {
		Scanner scanner =  new Scanner(System.in);
		n = scanner.nextInt();
		for(int i=0;i<n;i++){
			m[i]=scanner.nextInt();
			a[i]=scanner.nextInt();
		}
		long cnt = ctr(a,m,n);
		System.out.println(cnt);
		
	}
}

猜你喜欢

转载自blog.csdn.net/w1304636468/article/details/88776108