ACM专题学习四
题目
Fedya studies in a gymnasium. Fedya’s maths hometask is to calculate the following expression:
(1n + 2n + 3n + 4n) mod 5
for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).
Input
The single line contains a single integer n (0 ≤ n ≤ 10105). The number doesn’t contain any leading zeroes.
Output
Print the value of the expression without leading zeros.
Input
4
Output
4
Input
124356983594583453458888889
Output
0
分析
写一下表,发现为n是4的倍数时答案为4,否则为0,那就直接把数字除以4试试,由于输入的数字可能很长,所以用字符数组存,每次取出一个数,d=s[i]-'0',整个数字模4就是在把字符变数字时模4,[([d*10+(s[i]-'0')]*10+s[i+1]-'0')*10+……]%4等同于
[([([d*10+(s[i]-'0')]*10)%4+s[i+1]-'0']*10)%4……]%4,用sum记录最后结果,如果sum==0就输出4,否则输出0。但是最后超时了┭┮﹏┭┮。
代码如下
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn=1e5+10;
char s[maxn];
int d;
int main()
{
scanf("%s",s);
int sum=0;
for(int i=0;i<strlen(s);i++)
{
d=s[i]-'0';
// if(sum<10);
sum*=10;
sum+=d;
sum%=4;
}
// if(sum%4==0)
if(sum==0)
printf("4");
else printf("0");
}
有一个巧妙的发现是这个数是否能被4整除取决于最后这个数的两位(个位和十位),如果个位和十位组成的两位数能被4整除这整个数就能被4整除,否则不能被4整除。\(^o^)/~
代码
#include <iostream>//最后两位模四
#include <cstring>
using namespace std;
const int N = 1e5 + 10;
char s[N];
int main()
{
scanf("%s",s);
int ss = strlen(s);
int a ;
if(ss >= 2)
a = (s[ss-2]-'0')*10+s[ss-1]-'0' ;
else
a = s[0] - '0';
if(a%4 != 0)
printf("0");
else
printf("4");
return 0;
}