Problem code : CHEFINSQ ,, can anyone tell me whats wrong with this code? it is passing for 30 but not for 100

#include
#include
using namespace std;
long fact(int num)
{
if(num==0)
return 1;
else
return num*(fact(num-1));
}
int main(void)
{
int test;
cin>>test;
while(test–)
{
int n,k;
cin>>n>>k;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);

    int max=a[k-1];
    int counter_max=0;
    for(int i=0;i<n;i++)
    {
        if(max==a[i])
            counter_max++;
        if(a[i]>max)
            break;
    }
    int counter_prev=0;
    
    for(int i=0;i<n;i++)
    {
        if(a[i]<max)
            counter_prev++;
        else
            break;
    }
    int temp_count=k-counter_prev;

    cout<<fact(counter_max)/(fact(temp_count)*fact(counter_max-temp_count))<<endl;
}
return 0;

}

Actually you factorial function creating the issue. There is INTEGER OVERFLOW as counter_max can be as large as 49 and 49! would be to large for even long long int

1 Like