HDU 1395

来源:互联网 发布:相片排版软件 编辑:程序博客网 时间:2024/04/30 07:21

讲解转载自:杭电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
25
 

Sample Output
2^? mod 2 = 12^4 mod 5 = 1

0 0