Java:计算二项式系数 [英] Java: Calculating binomial coefficient
本文介绍了Java:计算二项式系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下程序计算两个整数的二项式系数。但我想改变程序,它只计算并保存解决方案所需的系数。
问题是我现在真的不知道怎么做。
守则
I have the following programm calculating the binomial coefficient of two integers. But I want to change the programm, that it calculates and saves only the necessary coefficients for the solution. The problem is that I have really no idea how to it, right now. The Code
public static long binomialIteration(int n, int k)
{
if(k<0 || n<k)
{
return 0;
}
long[][] h= new long[n+1][n+1];
for(int i=0; i<=n; i++)
{
h[i][0]=h[i][i]=1;
}
for(int i=1;i<=n;i++)
{
for(int j=0; j<=i; j++)
{
h[i][j] = (j==0 ? 0: h[i-1][j-1]) + (i == j ? 0 : h[i-1][j]);
}
}
return h[n][k];
}
推荐答案
这个此网站的代码
private static long binomial(int n, int k)
{
if (k>n-k)
k=n-k;
long b=1;
for (int i=1, m=n; i<=k; i++, m--)
b=b*m/i;
return b;
}
这篇关于Java:计算二项式系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文