pages:
  • 1
m.Yazdan SAYS

This function should work but I get the Wrong answer! What's the problem guys?

    int cal (int a){

int sum = 0;


while (a>=1) {
        int x = a%10;
        sum+=x;
        a/=10;
}

if (sum >= 10)
    return cal(sum);

else
    return sum;

}

AMiR SAYS

This function works fine for integers, the problem is the numbers on this problem are so huge that they couldn't fit into int or long long.

m.Yazdan SAYS

Thank you so much AMiR ;)

m.Yazdan SAYS

And I change this function and again I get the Wrong Answer. Can someone help me (particularly you MR.AMiR ;) )

long double cal (long double a){

long double sum = 0;


while (a>=1) {
        long double x = fmod(a,10);
        sum+=x;
        a=(a-x)/10;
}

if (sum >= 10)
    return cal(sum);

else
    return sum;

}

AMiR SAYS

You are very welcome.

The numbers are so big that they can only be read as strings.

I suggest you read them as strings and then iterate over all the digits and generate the total sum of them. The sum of those digits is much smaller than the original number and can fit into integer type.

Then you can treat with this summation as regular, just like what you did before.

Another smart thing that is good to know is you dont need to actually do like you did. Think about it mathematically. What summation of digits in a number means? It means the remainder of deviding the number by 9. See?

AMiR SAYS

BTW this snippet may clear what I'm saying:

string str;
cin >> str;
int sum = 0;
for(int i = 0; i < str.length(); i++) sum += in[i]-'0';

// treat 'sum' like input
m.Yazdan SAYS

WoW! It's a great point. Why I didn't know that! The problem solved! Thank you so much MR.AMiR. You are great.