NOIP 考前 数论复习

Posted on 2016-11-11 13:15  yyjxx2010xyu  阅读(168)  评论(0编辑  收藏  举报

POJ 2891

x=r1 (mod a1)

x=r2 (mod a2)

x=a1*x+r1,x=a2*y+r2;

a1*x-a2*y=r2-r1; 

用Extend_Gcd求出m1*x+m2*y=d; d=Gcd(x,y);

那么就可以解出原来的x=(x*(r2-r1)/d)

那么代入原式r1=a1*x+r1 新的a1=lcm(a1,a2);

 1 #include <cstdio>
 2 #define LL long long
 3 LL a1,a2,r1,r2,x,y,n; 
 4 LL Extend_Gcd(LL a,LL b,LL &x,LL &y)
 5 {
 6     if (b==0) {x=1,y=0; return a;}
 7     LL Ret=Extend_Gcd(b,a%b,x,y);
 8     LL Tmp=x;
 9     x=y; y=(Tmp-a/b*y);
10     return Ret;
11 }
12 int main()
13 {
14     // freopen("c.in","r",stdin);
15     while (scanf("%lld",&n)!=EOF)
16     {
17         scanf("%lld%lld",&a1,&r1); bool Ok=true;
18         for (LL i=1;i<n;i++)
19         {
20             scanf("%lld%lld",&a2,&r2);
21             LL a=a1,b=a2,m=r2-r1;
22             LL d=Extend_Gcd(a,b,x,y);
23             if (m%d) Ok=false;
24             x=(((x*m/d))%(b/d)+(b/d))%(b/d);
25             r1=x*a1+r1;
26             a1=(a1*a2)/d;
27         }
28         if (Ok) printf("%lld\n",r1); else puts("-1");
29     }
30     return 0;
31 }
POJ 2891

 POJ 2407 欧拉函数

 1 #include <cstdio>
 2 int n;
 3 int main()
 4 {
 5     while (scanf("%d",&n)!=EOF)
 6     {
 7         if (n==0) break;
 8         int Ans=1; int Tmp=n;
 9         for (int i=2;i*i<=Tmp;i++)
10             if (n%i==0)
11             {
12                 Ans=Ans*(i-1);
13                 n=n/i;
14                 while (n%i==0) Ans=Ans*i,n=n/i;
15             }
16         if (n>1) Ans=Ans*(n-1);
17         printf("%d\n",Ans);
18     }
19     return 0;
20 }
POJ 2407