2^x mod n = 1
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 9742 Accepted Submission(s): 3007
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
这题只会暴力,还有种简单快捷的方法我不会。。。
代码:(这份代码在ZOJ能AC,到了杭电就TLE了)
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<limits.h>
using namespace std;
int main()
{
long long n;
while(scanf("%lld",&n)!=EOF)
{
long long t=1;
if(n==1||n%2==0)
{
printf("2^? mod %lld = 1\n",n);
continue;
}
long long i;
for( i=1; ;i++)
{
t*= 2;
t%= n;
if(t==1)
{
//ans= i;
printf("2^%lld mod %lld = 1\n",i,n);
break;
}
}
}
return 0;
}
杭电,ZOJ都能AC代码:
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<limits.h>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
//long long t=1;
if(n==1||n%2==0)
{
printf("2^? mod %d = 1\n",n);
continue;
}
int t=2,i=1;
while(t!=1)
{
t=t*2%n;
i++;
}
printf("2^%d mod %d = 1\n",i,n);
}
return 0;
}
经过本人的多次测试发现:
该题在杭电上用longlong型会TLE滴,用__int64和int都能AC
在ZOJ上用__int64会CE滴,得用int和longlong才能AC