2^x mod n = 1 HDU1395
/*2^x mod n = 1 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 6738 Accepted Submission(s): 2022
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
Author MA, Xiao
Source ZOJ Monthly, February 2003 */
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
bool h[10000];
int main()
{
int n,k,n1,l,c;
while(scanf("%d",&n)!=EOF)
{
memset(h,0,sizeof(h));
k=0;l=1;c=2;
printf("2^");
if(n==1||n==2)
{
printf("? mod ");
printf("%d = 1\n",n);
continue;
}
n1=n;
while(c%n1!=1)
{
h[c]=1;
c*=2;
c=c%n1;
l++;
if(c!=1)
{
if(h[c]==1)//经典的比较方法,与前面的c比较,值得收藏。
{
k=1;
break;
}
else
h[c]=1;
}
}
if(k==1)
{
printf("? mod ");
printf("%d = 1\n",n);
continue;
}
else
{
printf("%d mod ",l);
printf("%d = 1\n",n);
}
}
return 0;
}//本题的为偶数时一定不到l,因为2^l=n*q+r.......r一定为偶数不会是1,所以可以把偶数单独拿出来。