0
点赞
收藏
分享

微信扫一扫

HDU1395---2^x mod n = 1


                                               2^x mod n = 1


                                         Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
                                                           Total Submission(s): 11563    Accepted Submission(s): 3588


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


 



Author


MA, Xiao


 



Source


​​ZOJ Monthly, February 2003​​


 


思路:大致题意:给定一个 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;

理解就能做出了。


/******************
Author:jiabenmuwei
sources:HDU1395
times:15ms
******************/
#include<stdio.h>
int main()
{

int n,i,j;
while(~scanf("%d",&n))
{
if(n%2==0||n<=1)
{
printf("2^? mod %d = 1\n",n);
continue;
}
int a=1;
for(i=1;;i++)
{
a*=2;
if(a%n==1)break;
a%=n;

}
printf("2^%d mod %d = 1\n",i,n);
}


}


C++:


#include<iostream>
using namespace std;
int main()
{
int i,n,a;
while(scanf("%d",&n)!=EOF)
{
if(n%2==0||n<=1)
{
printf("2^? mod %d = 1\n",n);
continue;
}
a=1;
for(i=1;; i++)
{
a*=2;
if(a%n==1)break;
a%=n;
}
printf("2^%d mod %d = 1\n",i,n);
}
return 0;
}





举报

相关推荐

0 条评论