Getting correct output but showing SIGSEGV ERROR ON SPOJ

#include <bits/stdc++.h>
using namespace std;
int check(int n,int count)
{
    static int dup;
    int rem,sum = 0;
    
    while(n!=0){
        rem = n%10;
        sum += pow(rem,2);
        n = n/10;
    }
    count++;
    if(count==1){
        dup = sum;
    }
    if(count>1 && dup==sum){
        return -1;
    }
    if(sum==1){
        return count;
    }
    check(sum,count);
}
int main() {
    int n;
    cin>>n;
    int res = check(n,0);
    cout<<res;
	return 0;
}

LINK TO THE QUESTION: SPOJ.com - Problem HPYNOS

@saurabh_negi Can you explain in plain english, what logic you are using.
As you are claiming that, your code is giving SIGSEGV error, then your program is violating the rules of memory access i.e. your program is incorrectly accessing memory location.
You can read about SIGSEGV Error here.

Now lets come to the problem, if you take a look at some of the test-cases given in the problem, you can see in case of n = 201 when you sum the square of digits until sum becomes 1, it would never reach one rather the cycle repeats again and again. So use this information to solve the problem.

In C++ you can use the set data-structure to store all the encountered sum till now, and if the current sum is already present in the set then ans = -1 else print the required answer i.e. after how many steps you get n = 1.

Solution in Python3 for your reference.

Thanks for reading.
Peace :v:

1 Like

what i was trying to do is that I was taking a duplicate variable and storing the first result in it and checking that if the future sum==dup then -1 is returned. Now I’ve realized the problem.