Waqar Ahmad
Waqar Ahmad

Reputation: 11

Runtime Error - SIGFPE

I HAVE THE FOLLOWING CODE for hackerearth competetion and WRITTEN IN C++ (g++ 4.8.4) it is giving SIGFPE on runtime I am just done with it

plz tell how tofix it

    #include<iostream>
    using namespace std;
    int factorial(int n);
   int main()
  {
   int n , k ,totitem , totways=0 , har1,har2, ansh=1;
int res;
cin>>n>>k;
totitem = (n/k);

ansh=factorial(n);

if(totitem>0)
for(int i=0;i<=totitem*k;i+=k)
{
    har1=factorial(i);
    har2=factorial(n-i);
    totways+=(ansh/(har1*har2));
}

cout<<totways;

return 0;
}
int factorial(int n)
{
if(n>1)
 return n*factorial(n-1);
 else
// if(n==0 || n==1)
 return 1;
}

Upvotes: -1

Views: 1184

Answers (1)

Palec
Palec

Reputation: 319

It is usually division by zero error.

There are two divide statements in your code.

1:

totitem = (n/k);

where you don't sanitise your input.

2:

har1=factorial(i);
har2=factorial(n-i);
totways+=(ansh/(har1*har2));

And this will fail if any of the har parameters equals to zero.

The most probable cause of the problem is that you are using 32-bit signed integers (int) to do factorial calculations, which are limited to factorial of 12! Trying to do factorial with larger numbers will cause overflow and thus incorrect result and eventually a zero value, that caused your runtime error.

Upvotes: 1

Related Questions