欧几里得算法求逆元

这里的逆元是啥?

例如给两个数,7,20。

因为7*3%20=1,则3就是7的逆元。一个数a与它逆元的乘积对b取余等于1。

求逆元的公式就是套一个模板,假如说我们求a关于b的逆元就是解这个方程:
a*x + b*y == 1,这个方程就可以直接求了。求出的x就是a关于b的逆元。

欧几里得算法模板:

void Ex_gcd(int a, int b, int &x, int &y)
{
    if(b == 0)//递归出口
    {
        x = 1;
        y = 0;
        return;
    }
    int x1, y1;
    Ex_gcd(b, a%b, x1, y1);
    x = y1;
    y = x1-(a/b)*y1;
}

可以试着做做HDU1756

http://acm.hdu.edu.cn/showproblem.php?pid=1576


不会的话,可以看我的解题报告:Hdu 1576:A/B

扩展欧几里得算法是一种求解线性同余方程 ax ≡ 1 (mod m) 中 x 的逆元的方法。逆元是指数值 x 使得 ax 与 m 取模之后的结果为 1。 下面是一个用 Java 实现扩展欧几里得算法求逆元的代码示例: ```java public class InverseElement { public static int extendedEuclidean(int a, int b) { int[] coeffs = new int[3]; // 存储扩展欧几里得算法求解的系数 int x = 0, y = 0; while (b != 0) { coeffs = updateCoeffs(a, b, coeffs); a = coeffs[0]; b = coeffs[1]; x = coeffs[2]; y = coeffs[3]; } if (a == 1) { return (x % m + m) % m; // 防止结果为负数 } else { return -1; // 没有逆元 } } private static int[] updateCoeffs(int a, int b, int[] coeffs) { if (b == 0) { coeffs[0] = a; coeffs[1] = b; coeffs[2] = 1; coeffs[3] = 0; return coeffs; } coeffs = updateCoeffs(b, a % b, coeffs); int x1 = coeffs[2]; int y1 = coeffs[3]; coeffs[2] = y1; coeffs[3] = x1 - (a / b) * y1; return coeffs; } public static void main(String[] args) { int a = 7; int m = 11; int inverse = extendedEuclidean(a, m); System.out.println("逆元: " + inverse); } } ``` 在上述代码中,`extendedEuclidean` 方法实现了扩展欧几里得算法, `updateCoeffs` 方法用于更新系数, `main` 方法用于测试求逆元的结果。在示例中,我们以 `a = 7` 和 `m = 11` 为例来求解逆元。 按照扩展欧几里得算法的步骤,我们递归调用 `updateCoeffs` 方法来更新系数,直到 b 为 0。然后,如果 a 为 1,则返回取模后的 x 值作为逆元;否则,返回 -1 表示没有逆元。 输出结果为:逆元:8,表示在模 11 下,7 的逆元为 8。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值