2^x mod n = 1
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7004 Accepted Submission(s):
2106
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.
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
//代码一:-----TLE #include<cstdio> #include<cstring> const int MAX=10000000; bool flag[MAX]; int main() { int n,i,k; while(~scanf("%d",&n)) { if((n&1)==0) printf("2^? mod 2 = 1\n"); else { memset(flag,false,sizeof(flag)); for(i=1,k=2;;++i) { if(k%n==1) { printf("2^%d mod %d = 1\n",i,n); break; } else if(flag[k%n]) { printf("2^? mod 2 = 1\n"); break; } else flag[k%n]=true; k<<=1; } } } return 0; } //代码二: copy代码:除了1和偶数不行,其他都是能找到的(but why????) int main(void) { int n; while(~scanf("%d",&n)) { if(n == 1 || n % 2 == 0) { printf("2^? mod %d = 1\n", n); continue; } int k = 1, ans = 2; while(ans != 1) { ans = ans *2 % n; k++; } printf("2^%d mod %d = 1\n", k, n); } return 0; } //代码三: #include <iostream> #include <cstdio> #include <cstring> using namespace std; bool h[10000]; int main() { int n,t,k; while(scanf("%d",&n)!=EOF) { if(n%2==0||n==1) { printf("2^? mod %d = 1\n",n); continue; } memset(h,false,n*sizeof(bool)); k=1; t=2; h[2]=1; while(t%n!=1) { k++; t<<=1; t=t%n; if(h[t]) break; h[t]=true; } if(t%n!=1) printf("2^? mod %d = 1\n",n); else printf("2^%d mod %d = 1\n",k,n); } return 0; }