Java: Calculating binomial coefficient

后端 未结 3 1808
渐次进展
渐次进展 2021-01-07 11:30

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 coeffi

相关标签:
3条回答
  • 2021-01-07 12:17

    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:

    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);
        }
    
    0 讨论(0)
  • 2021-01-07 12:18

    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;
        }
    
    0 讨论(0)
  • 2021-01-07 12:21

    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.

    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;
    }
    
    0 讨论(0)
提交回复
热议问题