HDU——1395 2^x mod n = 1(取模运算法则)

2^x mod n = 1

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 15197    Accepted Submission(s): 4695

Problem Description
Give a number n, find the minimum x(x>0) that satisfies 2^x mod n = 1.
 
Input
One positive integer on each line, the value of n.
 
Output
If the minimum x exists, print a line with 2^x mod n = 1.

Print 2^? mod n = 1 otherwise.

You should replace x and n with specific numbers.
 
Sample Input
2 5
 
Sample Output
2^? mod 2 = 1 2^4 mod 5 = 1
题目不难,就是要知道取模运算的基本法则这题主要是(a*b)%c=(a%c * b%c)%c.
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int main(void)
{
	int n;
	while (cin>>n)
	{
		if(n%2==0||n==1)//n为1或者偶数一定无解
			printf("2^? mod %d = 1
",n);
		else//奇数一定有解
		{
			int ans=1,t=2;
			while (t%n!=1)
			{
				t=(t*2)%n;//每次都求余数据就不会溢出
				ans++;
			}
			printf("2^%d mod %d = 1
",ans,n);
		}
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Blackops/p/5356432.html