Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Newton binomial coefficient in c++

Tags:

c++

I am having an issue with my program for the Newton Binomial Coefficients. At first it printed negative numbers but changing the factorial function type to unsigned long long seemed to have fixed the problem with printing negative numbers. The program works for max n = 20, above it starts printing zeros, ones and twos. No idea how to fix that and hopefully someone can give me a hand.

#include <iostream>
using namespace std;

unsigned long long factorial(int n) {
    if (n == 0) {
        return 1;
    }
    return n*factorial(n - 1);
}

void Binom(int n ,int k) {
    unsigned long long factorialResult;
    if (k > n) {
        return;
    }
    factorialResult = factorial(n) /(factorial(k) * factorial(n - k));
    cout << factorialResult << " ";
    if (n >= k) {
        Binom(n, k + 1);
    }
}
like image 390
CandyPanda Avatar asked Dec 19 '16 14:12

CandyPanda


People also ask

What would be the complexity of finding all the n binomial coefficients using dynamic programming approach?

Time complexity: O(2n)

How did Newton come up with binomial theorem?

Newton himself used the method as a way of finding areas under curves. He noticed certain patterns hidden in the integer binomial sequence appeared in relation with curves and then applied them to rationals, finally obtained the generalized binomial sequence and the generalized binomial theorem.


1 Answers

The factorials are typically very large, so you just have an integer overflow here. To fix this issue, you could implement any other algorithm of calculation C(n, k) not using factorials, for example:

unsigned long long C(unsigned n, unsigned k) {
    if (n == k || k == 0) {
        return 1; // There's exactly one way to select n or 0 objects out of n
    }
    return C(n - 1, k - 1) * n / k;
}

Here the following recurrent rule is used: C(n, k) = C(n - 1, k - 1) * n / k. It's very easy to prove since C(n, k) = n! / (k! (n-k)!) = (n/k) * (n-1)! / ((k-1)!(n-1-k+1)!).

like image 93
alexeykuzmin0 Avatar answered Sep 22 '22 16:09

alexeykuzmin0