ACM_同余+暴力找规律

小光的忧伤

Time Limit: 2000/1000ms (Java/Others)

Problem Description:

锴神:我尊重作者原意,你们出什么我就加什么。于是小光打了道水题(也就是这道),但是呢比赛的时候拿着自己的标程却AC不了,最后只能尴尬地打表!!为毛呢?!请你来看看这道题,为了缓解小光的尴尬,他决定不告诉你样例输入输出,神马?!没有输入输出?对,就是这么贼!

Input:

多组数据,输入n,求(1^n+2^n+3^n+4^n)mod 5,其中n范围是[10^5,10^(10^5)],数字可能有前导0

Output:

当然是结果啦~

Sample Input:

不给你

Sample Output:

就是不给你
解题思路:题目的意思很简单,已经提示要找规律,于是(快速幂)暴力枚举查找,发现如果是4的倍数,计算结果是4,否则为0。其中红色部分n的区间数的位数是5位数到10万位数,因此字符串长度开10^5+5即可。注意读取的字符串可能前导有0,所以要去掉前导的'0'。
测试代码:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long LL;
 4 LL mod_pow(LL base,LL n,LL mod){//快速幂
 5     LL res=1;
 6     while(n){
 7         if(n&1)res=res*base%mod;
 8         base=base*base%mod;
 9         n>>=1;
10     }
11     return res;
12 }
13 int main(){
14     LL sum=0;//测试
15     for(int i=100000;i<1000000;++i){
16         sum=(mod_pow(2,i,5)+mod_pow(3,i,5)+mod_pow(4,i,5)+1)%5;
17         cout<<i<<' '<<sum<<endl;
18         if(i%4==0)cout<<i<<"是可以的"<<endl;
19     }
20     return 0;
21 }
AC代码:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 char s[100005];
 4 int main(){
 5     while(cin>>s){
 6         int sum=0,j=0;
 7         while(s[j]=='0')++j;//去掉前导0
 8         for(int i=j;i<(int)strlen(s);++i)
 9             sum=(sum*10+(s[i]-'0')%4)%4;//同余方程
10         if(sum%4)cout<<'0'<<endl;//规律
11         else cout<<'4'<<endl;
12     }
13     return 0;
14 }
 

猜你喜欢

转载自www.cnblogs.com/acgoto/p/8990450.html