I have created this simple program using c to calculate combinations. But whenever I enter large value like 20,30,40.. for variable 'n' and for 'r' program output is not true. But this program works fine with small numbers like 5,7,10... How can i fix this problem to find combinations even input big numbers for n and r ?
Also I wanna use nCr = n-1Cr + n-1Cr-1 rule in this program and I am using C language
#include <stdio.h>
int fact(int i){
if(i <= 1){
return 1;
}
return i * fact(i-1);
}
int nCr(int n,int r){
int nCr;
if(r == 0 || n == r){
nCr = 1;
}else{
nCr = (fact(n-1)/(fact(r) * fact(n-1-r))) + (fact(n-1)/(fact(r-1) * fact(n-r)));
}
return nCr;
}
int main(){
int n,r;
printf("Enter n : ");
scanf("%d",&n);
printf("Enter r : ");
scanf("%d",&r);
printf("nCr value : %d\n",nCr(n,r));
return 0;
}
Thank you so much for your answers.
For large numbers use
long long int
instead ofint
. Try this instead: