Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program to calculates the number of ways to choose k objects from n distinct objects. 'k' and 'n' both are integers

I wrote a C program to calculate the number of ways to choose k objects from n distinct objects using functions.

    #include<stdio.h>
    long f(int a)
    {
     if(a==1||a==0)return(0);
     else return(a*f(a-1));
    }

    int combination(int N,int K)
    {
     long int NF,KF,NMKF;
     NF=f(N);
     KF=f(K);
     NMKF=f(N-K);
     return(NF/(KF*NMKF));

    }
    int main()
    {
     int n,k;
     scanf("%d%d",&n,&k);
     combination(n,k);
    }

But the compiler shows following error message

floating point exception (core dumped)

How to avoid it?

like image 933
Sri Harsha Avatar asked Dec 06 '22 20:12

Sri Harsha


2 Answers

The problem is in this line

if(a==1||a==0)return(0);

It should be

if(a==1||a==0)return(1);

While calculating factorial, n*(n-1)*(n-2)...*(2)*(1). Notice in the end, we multiply by 1 and not zero. multiplying with 0 would make the factorial 0. And later when you are performing division, the 0 comes in the denominator, and floating point exception is occurring. That's why your program is giving error.

For cases when factorial of 0 is needed. Then also this would work, because factorial of 0 is 1 and not 0.. Check this out.

like image 190
Haris Avatar answered May 12 '23 07:05

Haris


Two problems:

  1. if(a==1||a==0) you should return 1, not return 0. Because 1!=1, 0!=1.
  2. Your intention is choose k objects from n distinct objects. But You should add param checking in order to not occur the n<k. If we input n=2, k=3.The program will go to error. It is bad! I hope this can help you.
like image 21
cwfighter Avatar answered May 12 '23 07:05

cwfighter