杭电OJ1576-A/B(逆元)

题目链接:A/B

AC代码:

import java.util.Scanner;
public class Main {
    static long x;
    static long y;

    static long ext_gcd(long a, long b) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long res = ext_gcd(b, a % b);
        long x1 = x;
        x = y;
        y = x1 - a / b * y;
        return res;
    }

    static long linearEquation(long a, long b, long m) throws Exception {
        long d = ext_gcd(a, b);
        if (m % d != 0) {
            throw new Exception("无解");
        }
        long n = m / d;
        x *= n;
        y *= n;
        return d;
    }

    //求解逆元
    static long inverseElement(long a, long mo) throws Exception {
        long d = linearEquation(a, mo, 1);
        x = (x % mo + mo) % mo;//x要大于零
        return d;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        long n;
        long B;
        while (T-- != 0) {
            n = in.nextInt();
            B = in.nextInt();
            try {
                inverseElement(B, 9973);
                System.out.println(n * x % 9973);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值