3

I wrote a program which is supposed to print the value of Newton's binomial. number - number of tests, t[i][0] - n, t[i][1] - k. It seems to be ok for small numbers n and k, but when I want to type bigger numbers it prints 0, 1 or small, negative integer. Basically I used long intead of int so it should work with bigger numbers. Could you explain why is that?

#include <iostream>
long fact(int x);
using namespace std;
int main()
{
    int number;
    cin>>number;
    int t[number][2];

    for(int i=0; i<number; i++)
    {
        cin>>t[i][0];
        cin>>t[i][1];
        if (t[i][0]<t[i][1]) return 0;
    }

    for(int i=0; i<number; i++)
    {
        cout<<fact(t[i][0])/(fact(t[i][0]-t[i][1])*fact(t[i][1]))<<endl;
    }
    return 0;
}
long fact(int x)
{
    long factt=1;
    for(int i=1; i<=x; i++)
    {
        factt=factt*i;
    }
    return factt;
}

@edit

Thanks for advice. I tried implementing this but it doesn't compute the binomial well. It prints 11 for n=4 and k=2. May you have a look at this?

#include <iostream>

long fact(int n, int k);
using namespace std;
int main()
{
    int number;
    cin>>number;
    int t[number][2];

    for(int i=0; i<number; i++)
    {
        cin>>t[i][0];
        cin>>t[i][1];
        if (t[i][0]<t[i][1]) return 0;
    }
    for(int i=0; i<number; i++)
    {
        cout<<fact(t[i][0],t[i][1])<<endl;
    }
    return 0;
}

long fact(int n, int k)
{
    if(n==0 || n==k)
        return 1;
    else if(n>k)
        return fact(n-1,k-1)+fact(n-1, k);
    else
        return 0;
}
DominikM
  • 33
  • 3

2 Answers2

2

Factorial grows really fast and even unsigned 64-bit integers overflow n! for n>20. The overflow free way to implement the binomial coefficient is to use this recursive definition:

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

This ensures that you get an overflow only when binom(n,k) is too large to fit in your integral type's size.

Pradhan
  • 16,391
  • 3
  • 44
  • 59
0

On Linux 32bit long is the same as int and fits into 32bit. On Linux 64bit long is 64bit long. On Windows both 32bit and 64bit long is 32bits entity

You have to use long long to guaranteed to use 64bit, though it might be not enough to overcome overflow. Use recursive formula for binominal, if possible

Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64