简体   繁体   中英

Why does my code for SPOJ GCD2 error on SPOJ?

Following is code for SPOJ GCD2 . It's running well on my machine and Ideone, but getting runtime error (SIGFPE) on SPOJ. I have checked all the test cases also available at spojtoolkit.com.

I am unable to figure out why this code is showing runtime error (SIGFPE) on spoj. SIGFPE means Erroneous arithmetic operation.

Why is this code showing runtime error on SPOJ?

#include <bits/stdc++.h>

using namespace std;

int gcd(int x,int a)
{
    if(a==0)
        return x;
    else
        return gcd(a, x%a);
}


int getmod(string b,int a)
{
    int n=b.size();
    int d;
    d= (b[0]-'0') % a;
    for(int i=1; i!=n; i++)
    {
        d=d*10;
        d=d + (b[i]-'0');
        d= d % a;
    }
    return d;

}
int main()
{
    int tc;
    cin >> tc;
    int a;
    string b;
    while(tc--)
    {
        cin >>a>>b;
        int x=getmod(b,a);
        cout << gcd(x,a)<<endl;

    }
    return 0;
}
int getmod(string b,int a)
{
    int n=b.size();
    int d;
    d= (b[0]-'0') % a;

If a = 0 , this will error, because % 0 is like dividing by zero. a can be zero according to the problem statement.

The error covers division by zero :

The SIGFPE signal reports a fatal arithmetic error. Although the name is derived from “floating-point exception”, this signal actually covers all arithmetic errors, including division by zero and overflow. If a program stores integer data in a location which is then used in a floating-point operation, this often causes an “invalid operation” exception, because the processor cannot recognize the data as a floating-point number.

You can fix it by checking if a == 0 and simply returning b as the answer in that case. Else call your current function as is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM