寒假训练数论B

题目
Fedya studies in a gymnasium. Fedya’s maths hometask is to calculate the following expression:

(1^n  +  2^n + 3^n + 4^n) 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.
题目大意
给出一个数n,求(1^n  +  2^n + 3^n + 4^n) mod 5的值。
解题思路
先把1^n , 2^n, 3^n, 4^n的规律找出来。
然后再找(1^n  +  2^n + 3^n + 4^n) mod 5的规律。
规律当n为4的倍数时,输出4,其余情况输出0.
判断一个数是否为4的倍数(n很大)
法一 n%2为偶数
法二 判断n(n>=10)的最后两位是否为4的倍数,加上n<10 的特判
代码

#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
string st;
int main()
{
	freopen("b.in","r",stdin);
	freopen("b.out","w",stdout);
	char x;
	x='1';
	while (x!=EOF)
	{
		x=getchar();
		if (!(x>='0' && x<='9')) continue;
		st+=x;
	}

	if (st[st.size()-1]%2!=0) printf("0\n");
	else
	{
		int num=0;
		for (int i=0;i<st.size()-1;i++)
		  {
		  	num=num*10+st[i]-48;
		  	num=num%2;
		  }
		num=num*10+st[st.size()-1]-48;
		num/=2;  
		if (num%2==0) printf("4\n");
		else printf("0\n");  
	} 
}
发布了41 篇原创文章 · 获赞 0 · 访问量 593

猜你喜欢

转载自blog.csdn.net/weixin_45723759/article/details/104033967
今日推荐