Binomial Coefficient

This code is suppose to return the binomial coefficient of two numbers. It works fine for smaller values but goes haywire with larger values. Is there something im overlooking?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int binomial(int n, int k)
{
    int num, den ;
    if ( n < k ) 
    {
       return(0) ; 
    }
    else 
    {
	den = 1;
	num = 1 ; 
	for (int i =  1  ; i <= k   ; i = i+1)
	    den =    den * i;
	for (int j = n-k+1; j<=n; j=j+1)	
	    num = num * j;
	return(num/den);
    } 
}
It works fine for smaller values but goes haywire with larger values.


Can you give an example?

input / output / expected output


First thing that comes to mind is that you might be overflowing what an int can hold. In which case you'd have to use a larger variable.
Last edited on
ur right.. int cannot hold the large value.

96* 97*98*99*100 should be 9034502400

but the value it shows is 444567808

use double values instead of integers, also you need to use recursion...here is an example:

double fact(double n)
{
if (n == 0) return (1);
else

return (n * fact(n - 1));

}

now you call this function from an equation you have set up for your "num and den"
Last edited on
Topic archived. No new replies allowed.