HDU 1395 2^x mod n = 1
- 题目描述
Give a number n, find the minimum x(x>0) that satisfies 2^x mod n = 1.
- Inuput
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
- Tips:
题意:
求最小正整数x,使其满足2x mod n = 1,若找不到,则输出2^? mod n = 1.
分析:
由欧拉定理:
若n, a为正整数,且n, a互质,则
当2,n互质时,一定存在x,使
而当n = 1 或n为偶数时,2x mod n 不可能为1
所以分情况:
1°
当输入的n = 1 || n % 2 == 0时,输出2^? mod n = 1
2°
当输入的n ≥ 3 && n % 2 == 1时,暴力穷举i = 1 … INF.使用快速幂计算2i mod n是否为1,若为1则输出并break,否则i++.
因为测试数据较小,即使用暴力发也能AC.(但会卡cout所以请使用printf()).
- Answer:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int n;
int pow(long long i){
int ans = 1, base = 2;
while(i){
if(i & 1){
ans = ans * base % n;
}
base = base * base % n;
i >>= 1;
}
return ans % n;
}
int main(void){
while(cin >> n){
if(n % 2 == 0 || n == 1 ){
printf("2^? mod %d = 1\n", n);
}
else{
for(long long i = 1; ;i++){
if(pow(i) == 1)
{
printf("2^%lld mod %d = 1\n", i, n);
break;
}
}
}
}
return 0;
}