开发者

Binomial coefficient in Java (adapting the following source)

开发者 https://www.devze.com 2023-01-10 17:50 出处:网络
I have 2 parameters and I want the method to return an int result.. I was given this code but I don\'t understand naff all about binoms etc and don\'t know how to \"convert\" it

I have 2 parameters and I want the method to return an int result.. I was given this code but I don't understand naff all about binoms etc and don't know how to "convert" it has double BC[126][126]; defined somewhere above it. But i don't need that i just want a result for these n and m. (I probably sound like numpty for putting like that)

private void 开发者_JS百科binom(int n, int m) {
    int i, j;

    if (n>=0)
        if (m>n||m<0) System.err.println("Illegal m!!\n");

        else { 
            for(i=0;i<=n;i++) BC[i][0] = 1;
            for(i=1;i<=m;i++) BC[0][i] = 0;
            for(j=1;j<=m;j++) for(i=1;i<=n;i++) 
                BC[i][j] = BC[i-1][j-1] + BC[i-1][j];
        }

    else System.err.println("Negative n!!\n");
}


You could just return BC[n][m] which is the element you calculate with the three for cycles..

by the way you have at least three possible implementations:

  • trivial recursive
  • this one (dynamic programming)
  • using the formula n! / (n-m)!m! which is no good since fact operations are annoying

A correction: your approach would be dynamic programming if you avoid to recalculate all the coefficients everytime the method gets invoked but it is not your case..


See the article Computing Binomial Coefficients for an example with comparable complexity, O(n2), but using only O(n) space instead of O(n2).

0

精彩评论

暂无评论...
验证码 换一张
取 消