- 1
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;
}
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
.
Thank you so much AMiR ;)
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;
}
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?
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
WoW! It's a great point. Why I didn't know that! The problem solved! Thank you so much MR.AMiR. You are great.
In order to post something you must login first. You can use the form in the top of this page.