2^x mod n = 1
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 15722 Accepted Submission(s): 4871
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
Sample Output
2^? mod 2 = 1 2^4 mod 5 = 1
Author
MA, Xiao
Source
ZOJ Monthly, February 2003
AC代码:
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<algorithm>
#include<time.h>
typedef long long LL;
using namespace std;
int q_mod(long long a,int b,int c) //快速幂取模
{
long long ans=1;
while(b>0)
{
if(b&1) //b&1相当于b%2==1
ans=(ans*a)%c;
b>>=1; //右移
a=(a*a)%c;
}
return ans;
}
int main()
{
int x,n;
while(cin>>n)
{
if(!(n&1)||n<=1)
cout<<"2^? mod "<<n<<" = 1"<<endl;
else
{
for(int i=1;;i++)
if(q_mod(2,i,n)==1)
{
cout<<"2^"<<i<<" mod "<<n<<" = 1"<<endl;
break;
}
}
}
}