曹旭辉 发表于 2025-3-19 17:56:04

在处理欧拉函数时如何利用逆元

https://i-blog.csdnimg.cn/direct/878131fbf2704b55b8dcfd98a1aff7b2.png
1. 逆元的引入

在盘算欧拉函数时,如果 (n) 是质数,那么 (\phi(n) = n - 1),这是直接的结果。然而,当 (n) 是合数时,我们需要处理分母中的质因数 (p_i)。
为了高效盘算 (\phi(n)),尤其是在编程实现中,我们可以利用 模逆元 来处理分母中的 (p_i)。这是由于在模运算中,除法需要通过乘法逆元来实现。
2. 模逆元的界说

https://i-blog.csdnimg.cn/direct/791df90fa4c44139b4d858796f8e9016.png
3. 欧拉函数公式中的逆元处理


[*] 盘算 (p_i) 的逆元:
https://i-blog.csdnimg.cn/direct/06f49e86fe834931bab329ba94692959.png
[*] 直接盘算分数:
https://i-blog.csdnimg.cn/direct/f00ef19c00354806b230ed1001b72122.png
4. 编程实现中的逆元处理

在编程实现中,如果我们需要在模 (M) 下盘算欧拉函数(比方在密码学中),可以利用 扩展欧几里得算法 来盘算逆元。
C++ 实现

#include <iostream>
#include <vector>
using namespace std;

// 扩展欧几里得算法求逆元
int extendedGCD(int a, int b, int &x, int &y) {
    if (a == 0) {
      x = 0;
      y = 1;
      return b;
    }
    int x1, y1;
    int gcd = extendedGCD(b % a, a, x1, y1);
    x = y1 - (b / a) * x1;
    y = x1;
    return gcd;
}

// 计算 a 在模 m 下的逆元
int modInverse(int a, int m) {
    int x, y;
    int gcd = extendedGCD(a, m, x, y);
    if (gcd != 1) {
      return -1; // 逆元不存在
    } else {
      return (x % m + m) % m; // 确保结果为正
    }
}

// 计算欧拉函数
int eulerPhi(int n) {
    int result = n;
    for (int p = 2; p * p <= n; p++) {
      if (n % p == 0) {
            while (n % p == 0) {
                n /= p;
            }
            result -= result / p;
      }
    }
    if (n > 1) {
      result -= result / n;
    }
    return result;
}

int main() {
    int n = 10;
    cout << "Euler's Totient Function for n = " << n << ": " << eulerPhi(n) << endl;
    return 0;
}
5. 总结



[*]在欧拉函数的公式中,(\frac{1}{p_i}) 可以通过直接盘算分数 (\frac{p_i - 1}{p_i}) 来处理。
[*]如果需要模运算下的欧拉函数,可以利用扩展欧几里得算法盘算逆元。
[*]欧拉函数的盘算在数论和密码学中有重要应用,比方 RSA 加密算法。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 在处理欧拉函数时如何利用逆元