CodeForces - 456B Fedya and Maths 打表找规律

GDUT 2020寒假训练 数论 B

原题链接

题目

原题截图
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 ≤  1 0 1 0 5 10^{10^5} ). The number doesn’t contain any leading zeroes.

Output
Print the value of the expression without leading zeros.

样例

input

124356983594583453458888889

output
0

题目大意

输入n 输出 ( 1 n + 2 n + 3 n + 4 n ) m o d 5 (1^n+2^n+3^n+4^n) mod 5 的值

思路

打表找规律
首先观察数据范围,肯定要用字符串进行输入,而且 1 0 1 0 5 10^{10^5} 这样一个数据量肯定是O(1)的算法,那么先打表找一找有什么规律

for(int i=1;i<=10;i++)
	{
		cout<<i<<" ";
		cout<<(int)(1+pow(2,i)+pow(3,i)+pow(4,i))%5<<endl;
	}

输出
输出
观察输出可以发现,答案4个为一循环,逢4的倍数答案是4,其余都为0。
那么就明确了,输入的n如果是4的倍数就输出4,不是则输出0。
那么下一个问题,如何判断输入字符串是否是4的倍数。
我们将字符串进行拆分,比如输入端字符串为“abcdefg”代表一个7位数,我命将其拆分成“abcde00”+“fg”两个数字相加的形式,那么前者是100的倍数,而100的倍数肯定能被4整除,那么原问题“abcdefg”能否被4整除就转化为“fg”能否被4整除,也就是我们只需要判断这个字符串的尾2位数组合能否被4整除即可。

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cmath>
using namespace std;
int main()
{
	/*for(int i=1;i<=10;i++)
	{
		cout<<i<<" ";
		cout<<(int)(1+pow(2,i)+pow(3,i)+pow(4,i))%5<<endl;
	}*/
	
	string str;
	cin>>str;
	int last2=0;;
	last2+=str[str.size()-1]-'0';
	last2+=(str[str.size()-2]-'0')*10;
	cout<<(last2%4==0?4:0)<<endl;
	return 0;
}

发布了33 篇原创文章 · 获赞 1 · 访问量 676

猜你喜欢

转载自blog.csdn.net/xcy2001/article/details/104773200