2^x mod n = 1
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6825 Accepted Submission(s): 2049
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
思路:给定一个 n 值, 求出满足式: 2^x mod n = 1 的最小 x 值;
1): 2^n 为偶数, n 为偶数就直接 pass 了, n 为奇数时肯定有结果(退出循环条件)
2): 两个容易 TLE 的地方:
只判断了 n 是否为偶数, 没有考虑到 n <= 1的情况(因为 x > 0)
在累乘第一个操作数时, 没有取模运算, 导致值太大, TLE; 第一个操作数2^n
取模理解: (a * b) % n = (a % n * b % n) % n;
AC代码:
#include<iostream>
using namespace std;
int main()
{
int i,n,flg,s;
while(scanf("%d",&n)!=EOF)
{
if(n%2==0||n<=1)
{printf("2^? mod %d = 1\n",n);continue;}
s=1;
for(i=1;;i++)
{
s*=2;
if(s%n==1)break;
s=s%n;
}
printf("2^%d mod %d = 1\n",i,n);
}
return 0;
}