2^x mod n = 1
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
题意:
找到最小的x使得 2x mod n=1 2 x m o d n = 1
根据欧拉定理我们知道如果2和n不互质x一定不存在,但是还要注意当n = 1的时候因为他很特殊所有数模1都是0,所以也无解
因此根据求欧拉函数可得到一个值使得x满足上式,但不一定是最小的,所以还有从小于phi的数内枚举一遍。。当然了也可以直接一开始就暴力枚举
code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
ll Euler(ll n){
ll ans = n;
for(ll i = 2; i * i <= n; i++){
if(n % i == 0){
ans = ans / i *(i - 1);
while(n % i == 0) n /= i;
}
}
if(n != 1){
ans = ans / n * (n - 1);
}
return ans;
}
ll gcd(ll a,ll b){
return b ? gcd(b,a%b) : a;
}
ll q_pow(ll a,ll b,ll mod){
ll ans = 1;
while(b){
if(b & 1)
ans = ans * a % mod;
b >>= 1;
a = a * a % mod;
}
return ans;
}
int main(){
ll n;
while(~scanf("%lld",&n)){
if(gcd(2LL,n) != 1 || n == 1){
printf("2^? mod %lld = 1\n",n);
}
else{
ll phi = Euler(n);
ll ans = phi;
for(ll i = 2; i <= phi; i++){
if(q_pow(2LL,i,n) == 1){
ans = i;
break;
}
}
printf("2^%lld mod %lld = 1\n",ans,n);
}
}
return 0;
}