51nod-1079 中国剩余定理

来源:互联网 发布:淘宝登录界面刷不出来 编辑:程序博客网 时间:2024/06/01 08:48

1079 中国剩余定理

一个正整数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。
Input示例
3
2 1
3 2
5 3
Output示例

23


传送门:中国国剩余定理


AC代码:



一:暴力

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int MAX = 1e3+10;struct node{    int p,m;}s[MAX];int main(){    int n;    while(scanf("%d", &n) != EOF)    {        for(int i=0; i<n; i++)            scanf("%d%d",&s[i].p,&s[i].m);        int ans=s[0].m,temp=1;        for(int i=0;i<n-1;i++)        {            temp*=s[i].p;            while(ans%s[i+1].p!=s[i+1].m)            {                ans+=temp;            }        }        printf("%d\n",ans);    }    return 0;}


二:



#include<cstdio>  typedef long long LL;  void exgcd(LL a,LL b,LL &x,LL &y)  {      if(b==0)      {          y=0;x=1;      }       else      {          exgcd(b,a%b,y,x);          y-=x*(a/b);       }   }   int main()  {      LL n,p[100],k[100],i;      LL M=1;      scanf("%lld",&n);      for(i=0;i<n;++i)      {          scanf("%lld%lld",&p[i],&k[i]);          M*=p[i];       }       LL ans=0;      for(i=0;i<n;++i)      {          LL Mi=M/p[i],x,y;          exgcd(Mi,p[i],x,y);           ans=(ans+Mi*k[i]*x)%M;       }       if(ans<0)          ans+=M;      printf("%lld\n",ans);       return 0;  }
原创粉丝点击