[TJOI2009] 猜数字

洛谷 P3868 传送门

CRT裸题......

我为了复习数论,用CRT和EXCRT分别把这道题写了一遍QAQ

CRT:

 1 #include<cstdio>
 2 #define ll long long
 3 
 4 int n;
 5 ll bp=1,ans;
 6 ll aa[15],bb[15];
 7 
 8 void exgcd(ll a,ll b,ll &x,ll &y)
 9 {
10     if(!b)
11     {
12         x=1,y=0;
13         return;
14     }
15     exgcd(b,a%b,y,x); 
16     y-=a/b*x;
17 }
18 
19 ll mul(ll a,ll b,ll mod)
20 {
21     ll ret=0;
22     while(b)
23     {
24         if(b&1)ret=(ret+a)%mod;
25         a=(a+a)%mod;
26         b>>=1;
27     }
28     return ret;
29 }
30 
31 int main()
32 {
33     scanf("%d",&n);
34     for(int i=1;i<=n;i++)scanf("%lld",&aa[i]);
35     for(int i=1;i<=n;i++)scanf("%lld",&bb[i]),bp=bp*bb[i];
36     for(int i=1;i<=n;i++)
37     {
38         aa[i]=(aa[i]%bb[i]+bb[i])%bb[i];
39         ll bt=bp/bb[i];
40         //bt*inv+bb[i]*k=1
41         ll inv,k;
42         exgcd(bt,bb[i],inv,k);
43         inv=(inv%bb[i]+bb[i])%bb[i];
44         ans=(ans+mul(mul(bt,inv,bp),aa[i],bp))%bp;
45     }
46     printf("%lld",ans);
47     return 0;
48 }
CRT

EXCRT:

 1 #include<cstdio>
 2 #define ll long long
 3 
 4 int n;
 5 ll aa[15],bb[15];
 6 ll bp=1,ans;
 7 
 8 ll exgcd(ll a,ll b,ll &x,ll &y)
 9 {
10     if(!b)
11     {
12         x=1,y=0;
13         return a;
14     }
15     ll ret=exgcd(b,a%b,y,x);
16     y-=a/b*x;
17     return ret;
18 }
19 
20 ll mul(ll a,ll b,ll mod)
21 {
22     ll ret=0;
23     while(b)
24     {
25         if(b&1)ret=(ret+a)%mod;
26         a=(a+a)%mod;
27         b>>=1;
28     }
29     return ret;
30 }
31 
32 int main()
33 {
34     scanf("%d",&n);
35     for(int i=1;i<=n;i++)scanf("%lld",&aa[i]);
36     for(int i=1;i<=n;i++)scanf("%lld",&bb[i]);
37     for(int i=1;i<=n;i++)
38     {
39         ll c=((aa[i]-ans)%bb[i]+bb[i])%bb[i];
40         ll k,kk;
41         ll g=exgcd(bp,bb[i],k,kk);
42         c/=g,bb[i]/=g;
43         k=mul(k,c,bb[i]);
44         ans=ans+k*bp;
45         bp=bp*bb[i];
46         ans=(ans%bp+bp)%bp;
47     }
48     printf("%lld",ans);
49     return 0;
50 }
EXCRT

 

posted @ 2018-10-16 16:43  cervusky  阅读(211)  评论(0编辑  收藏  举报

Contact with me