您的位置:首页 > 其它

HDU 1395

2014-01-21 12:42 148 查看
讲解转载自:杭电Discuss

1)当n为1,无解。

2)n为偶数2^x显然为偶数,而1为奇数,2^n和1不可能关于n同余,x无解。

3)n为奇数时(n与2互素),由费尔马定理知当x=n-1为一解(但不一定是最小),此时暴力即可。值得注意的是,暴力时为了减小运算量,可以先取摸,再乘2,即代码中的i=(i%n)*2。否则会TLE。

代码(G++):

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
int n,x,t;
while(cin>>n)
{
if(0==n%2||1==n)  cout<<"2^? mod "<<n<<" = 1"<<endl;
else{
t=2;
for(x=1;x<50000;x++)
{
if(1==t%n)
{
cout<<"2^"<<x<<" mod "<<n<<" = 1"<<endl;
break;
}else t=t%n*2;
}
}
}
system("PAUSE");
return EXIT_SUCCESS;
}


附上原题:


2^x mod n = 1

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)



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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: