hdu1395 2^x mod n = 1(数论:快速幂取模+欧拉定理)

本文探讨了如何通过欧拉定理解决特定模运算问题,包括快速幂取模法和利用欧拉函数找到上界的方法,适用于奇数n的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

欧拉定理的形式: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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值