码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-02-05 20:32:34      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:public   import   mic   static   strong   stat   imp   return   pre   

 技术图片

 

 

 

 

    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));
                }
        }
}

 

 

技术图片

 

 

 

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

标签:public   import   mic   static   strong   stat   imp   return   pre   

原文地址:https://www.cnblogs.com/qdu-lkc/p/12266165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!