zoukankan      html  css  js  c++  java
  • 887. 求组合数 III(模板 卢卡斯定理)

     

     

        a,b都非常大,但是p较小

        前边两种方法都会超时的  N^2 和NlongN

        可以用卢卡斯定理  P*longN*longP

        

           定义:

    代码:

    import java.util.Scanner;
    
    public class Main{
            static int p;
            //快速幂
            static long quick_pow(long a,long b){
                    long res=1;
                    while(b>0){
                            if((b&1)==1) res=res*a%p;
                            a=a*a%p;
                            b>>=1;
                    }
                    return res;
            }
            //根据组合数定义求C(a,b)
            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*quick_pow(i,p-2)%p;
                    }
                    return res;
            }
            //卢卡斯定理
            static long lucas(long a,long b){
                    if(a<p && b<p) return C(a,b);
                    return C(a%p,b%p)*lucas(a/p,b/p)%p;
            }
            public static void main(String[] args) {
                    Scanner scan=new Scanner(System.in);
                    int t=scan.nextInt();
                    while(t-->0){
                            long a=scan.nextLong();
                            long b=scan.nextLong();
                            p=scan.nextInt();
                            System.out.println(lucas(a,b));
                    }
            }
    }

     

     

     

  • 相关阅读:
    mysql数据库 详解
    0810 smarty
    抽象类
    Nginx 负载均衡策略
    Nginx 负载均衡配置和策略
    内置Web Server
    PHP运行方式
    MySQL create table 语法
    MySQL 索引的使用
    MySQL的 explain 解析
  • 原文地址:https://www.cnblogs.com/qdu-lkc/p/12266165.html
Copyright © 2011-2022 走看看