快速组合数

快速组合数

double f[N+10];

f[0]=0;

for(int i=1;i<=N;i++)

 f[i]=f[i-1]+log(i*1.0);

double logC(int n,int m)

{

 return f[n]-f[m]-f[n-m];

}//返回log( C(n,m) )


组合数的常用公式:

c[n][m] = c[n-1][m-1] + c[n-1][m]


c[n][m] = c[n][m-1]*(n-m+1)/m


¥¥   求C(n,m) % p    (n=1e6 , p为质数)

设 C(n,m) =  n!  /   (m! * (n-m)! )   %p   =     x 

则     n!  /   (m! * (n-m)! )    =  p*y  + x 

令    (m! * (n-m)! ) = Q

两边同乘Q^(p-1)得

n!  *   Q^(p-2)  = (p*y+x) * Q^(p-1)

两边模p 得   (费马小定理)

n! %p * [Q^(p-2)]%p = x

即 C(n,m)% P =  n! %p * [(m! * (n-m)! )^(p-2)]%p


### Java 实现高效计算组合数 为了提高组合数计算效率,在Java中可以采用预处理阶乘及其逆元的方式,从而使得每次查询的时间复杂度降低到O(1),而预处理时间复杂度为O(n log n)[^2]。 下面展示了一个基于模运算下的快速幂以及组合数求解方法: ```java import java.util.Arrays; public class CombinationCalculator { private static final int MOD = (int) 1e9 + 7; public static void main(String[] args) { long startTime = System.currentTimeMillis(); int maxN = 1000; // 预设最大n值 long[] factorial = new long[maxN + 1]; long[] inverseFactorial = new long[maxN + 1]; preprocess(factorial, inverseFactorial); int n = 500; int k = 250; System.out.println(combine(n, k, factorial, inverseFactorial)); long endTime = System.currentTimeMillis(); System.out.println("Time cost: " + (endTime - startTime)); } private static void preprocess(long[] fact, long[] invFact){ int N = fact.length - 1; fact[0] = invFact[0] = 1; for(int i=1;i<=N;++i){ fact[i]=fact[i-1]*i%MOD; invFact[i]=(long)((modInverse(fact[i], MOD)))*invFact[i-1]%MOD; } } private static int combine(int n,int r,long[] f,long[] fi){ if(r>n || r<0)return 0; return (int)(f[n]*(fi[r]*fi[n-r])%MOD); } private static long modInverse(long a, long m){ long m0=m,y=0,x=1; if(m==1)return 0; while(a>1){ long q=a/m; long t=m; m=a%m;a=t;t=y;y=x-q*y;x=t; } if(x<0)x+=m0; return x; } } ``` 此程序首先通过`preprocess()`函数预先计算并存储所有不大于设定上限的阶乘和其对应的逆元。之后调用`combine()`来获取指定参数下组合数的结果。这种方法特别适合多次询问同一范围内的不同组合数值的情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值