AcWing 887. 求组合数 III (卢卡斯定理)

题目
组合数第三节,这次给的ab非常大达到1e18的级别,显然预处理硬算不行,这题用到卢卡斯定理。
需要取模的题目真是一个取模漏了数字就超了…
代码中C的公式是C约分后的计算方式,不难理解。

在这里插入图片描述
在这里插入图片描述

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);

    static int p;

    public static void main(String[] args) throws IOException {
        String[] s = br.readLine().split(" ");
        int n = Integer.parseInt(s[0]);
        for (int i = 0; i < n; i++) {
            s = br.readLine().split(" ");
            long a = Long.parseLong(s[0]);
            long b = Long.parseLong(s[1]);
            p = Integer.parseInt(s[2]);
            pw.println(lucas(a, b, p));
        }

        pw.println(C(8, 5));

        pw.flush();
        br.close();
    }

    public static long lucas(long a, long b, int p) {
        if (a < p && b < p) return C(a, b);
        return C(a % p, b % p) * lucas(a / p, b / p, p) % p;
    }

    private static long C(long a, long b) {
        long res = 1;
        for (long i = 1, j = a; i <= b; i++, j--) {
            res = res * j % p;
            res = res * qmi(i, p - 2) % p;
        }
        return res;
    }

    private static long qmi(long a, int k) {
        long res = 1;
        while (k != 0) {
            if ((k & 1) > 0) res = res * a % p;
            a = a * a % p;
            k >>= 1;
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值