-1

This is the iterative version, but it calls a recursive function. Would that have an effect on its time/space complexity?

int factorial(int n) {
    if (n == 1) {
        return 1;
    }
    else {
        return n * factorial(n - 1);
    }
}

int binomial_coefficient_iterative(unsigned int n, unsigned int k) {
    if (k == 0 || k == n) {
        return 1;
    }
    else {
        return (factorial(n) / ( factorial(k) * factorial(n - k) ) );
    }
}

This is the recursive version, calculated using the C(n, k) = C(n-1, k) + C(n-1, k-1) formula.

int binomial_coefficient_recursive(unsigned int n, unsigned int k){
    if (k == 0 || k == n) {
        return 1;
    }
    else {
        return binomial_coefficient_recursive(n - 1, k) + binomial_coefficient_recursive(n - 1, k - 1);
    }
}

Last but not least, can you calculate the binomial coefficient C(n, k) by using C(n, k-1)?

NeVada
  • 127
  • 9

1 Answers1

1

Both the solution depends on recursion. In 1st version you can replace the recursive call of factorial with simple iteration.

However, there is a issue of recalculation of overlapping sub problems in the 2nd solution.

  C(n, k) = C(n-1, k) + C(n-1, k-1) 

You should use memoization to cache the values of C(n,k) whenever it is computed store the value and when the function calls with the same parameteres instead re computation, lookup and return the value.

In the first problem you are making multiple calls to factorial function which could be avoided. The strategy is to compute the incremental change. For example when you compute factorial(k) you can derive

    factorial(n) = factorial(k) * K+1 * K+2 ...n

This reduces number of multiplication you are doing.

Coming back to the space time complexity of the problem.

1st: Time complexity is O(n) here as for 3 factorial calls you are doing n,k and n-k multiplication

2nd: It will be

    T(n,k) = T(n-1,k) + T(n-1,k-1) + O(1)           
    where T(n,n) = T(n,0) = O(1)

Solving this difference equation you will get T(n) = O(2^n) , (Same argument used in finding complexity of fibonacci series)

So the later approach is exponential which can be brought down using memoization.

Avishek Bhattacharya
  • 6,534
  • 3
  • 34
  • 53