欧拉定理的形式:a^f(n) = 1(mod n) a取任意正整数,n>1
对于该题条件可变形为:2^x-1 = n*k,n*k必须为奇数;
所以明显可知n等于2倍数时,不存在x满足条件
n=1时同样不存在x满足条件
只需看n为奇数时,有两种方法:
1、快速幂取模暴力,跑了500+ms,代码如下:
#include <cmath>
#include <iostream>
using namespace std;
#define LL long long
#define MAXN 10000
LL p[MAXN];
int cnt;
LL Pow(LL a, LL b, LL c) {
LL ans = 1;
while(b) {
if(b & 1)
ans = ans*a%c;
a = a*a%c;
b >>= 1;
}
return ans%c;
}
int main(void) {
LL n, ans;
while(cin >> n) {
if(n%2==0 || n==1) {
cout << "2^? mod " << n << " = 1" << endl;
}
else {
cnt = 0;
for(int i=1; ; ++i) {
if(Pow(2, i, n) == 1) {
ans = i;
break;
}
}
cout << "2^" << ans << " mod " << n << " = 1" << endl;
}
}
return 0;
}
2、欧拉定理找到满足条件的上界,再暴力,跑了46ms
因为f(n)一定满足条件,所以找到f(n)的值,再找到所有因子并排序,判断其因子是否满足条件
代码如下:
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
#define LL long long
#define MAXN 10000
LL p[MAXN];
int cnt;
int euler_phi(LL n) {
LL ans = n, i;
LL m = (LL)sqrt(n+0.5);
for(i=2; i<=m; ++i) {
if(n%i == 0) {
ans = ans*(i-1)/i;
n /= i;
while(n%i == 0) {
n /= i;
}
}
}
if(n > 1) {
ans = ans/n*(n-1);
}
return ans;
}
void find(LL n) {
p[cnt++] = n;
for(int i=2; i*i<=n; ++i) {
if(n%i == 0) {
if(i*i == n)
p[cnt++] = i;
else {
p[cnt++] = i;
p[cnt++] = n/i;
}
}
}
}
LL Pow(LL a, LL b, LL c) {
LL ans = 1;
while(b) {
if(b & 1)
ans = ans*a%c;
a = a*a%c;
b >>= 1;
}
return ans%c;
}
int main(void) {
LL n, ans;
while(cin >> n) {
if(n%2==0 || n==1) {
cout << "2^? mod " << n << " = 1" << endl;
}
else {
cnt = 0;
ans = euler_phi(n);
find(ans);
sort(p, p+cnt);
for(int i=0; i<cnt; ++i) {
if(Pow(2, p[i], n) == 1) {
ans = p[i];
break;
}
}
cout << "2^" << ans << " mod " << n << " = 1" << endl;
}
}
return 0;
}