Java:计算二项式系数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36925730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Calculating binomial coefficient
提问by MassU
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];
}
回答by Mad Matts
Do you want to keep your code afterall? Because you can also compute the binominal coefficient recursively, which would reduce your function to these 4 lines:
毕竟你想保留你的代码吗?因为您还可以递归计算二项式系数,这会将您的函数减少到以下 4 行:
static long binomi(int n, int k) {
if ((n == k) || (k == 0))
return 1;
else
return binomi(n - 1, k) + binomi(n - 1, k - 1);
}
回答by Chris Sherlock
What about this Code from this site
这个网站的代码怎么样
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;
}
回答by dmuir
You don't say which coefficients youi need. If you need C(N,n) for some fixed N, you could translate the C code below, which uses a one dimensional array. After the call, C[n] will hold the binomial coefficient C(N,n) for 0<=m<=N, as long as N is at most 66 -- if you need bigger N you will need to use an integral type with more bits.
你没有说你需要哪些系数。如果某些固定 N 需要 C(N,n),则可以翻译下面使用一维数组的 C 代码。调用后,C[n] 将保持二项式系数 C(N,n) 为 0<=m<=N,只要 N 最多为 66 - 如果您需要更大的 N,则需要使用积分输入更多位。
static int64_t* pascals_triangle( int N)
{
int n,k;
int64_t* C = calloc( N+1, sizeof *C);
for( n=0; n<=N; ++n)
{ C[n] = 1;
k = n;
while( --k>0)
{ C[k] += C[k-1];
}
}
return C;
}