887. 求組合數 III(模板 盧卡斯定理)

 

 

 

 

 

    a,b都很是大,可是p較小java

    前邊兩種方法都會超時的  N^2 和NlongNui

    能夠用盧卡斯定理  P*longN*longPspa

    

 

 

 

       定義:code

 

 

代碼:blog

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

 

 

相關文章
相關標籤/搜索