转载请注明出处:http://blog.csdn.net/u012860063
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1395
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
1)当n为1,无解。
2)n为偶数2^x显然为偶数,而1为奇数,2^n和1不可能关于n同余,x无解。
3)n为奇数时(此时暴力即可)
值得注意的是,暴力时为了减小运算量,可以先取摸,再乘2,即代码中的i=(i%n)*2。否则会TLE。
代码如下:
#include <cstdio>
int main()
{
int n,i;
while(~scanf("%d",&n))
{
if(n == 1 || n%2 == 0)
{
printf("2^? mod %d = 1\n",n);
continue;
}
int sum = 2;
for(i = 2 ; ; i++)
{
sum=(sum%n) * 2;
if(sum%n == 1)
break;
}
printf("2^%d mod %d = 1\n",i,n);
}
return 0;
}
本文介绍了一个算法问题,即寻找满足2^x模n等于1的最小正整数x的方法。文章通过分析n的不同情况给出了相应的解题思路,并提供了一段C++代码实现,特别指出对于奇数n的情况可通过不断取模来减少运算量。
2047

被折叠的 条评论
为什么被折叠?



