Reputation: 37
This worked on many cases, where most of the variables were ints, except when I wanted to find all the 10 digit numbers that add to, say, 45, then it just gave me an output of zero. Then, I changed all the variables to longs to see if that would make a difference, but it didn't. Any idea on what I should do or am currently doing wrong?
Any help is appreciated.
My program is as follows:
long add_digits(long);
int main()
{
long digit, i, j, limit, l, n, sum=0, rem, result, counter=1;
printf("\nInput digits: ");
scanf("%d", &j);
printf("\nInput number: ");
scanf("%d", &i);
limit=pow(10,j);
for(n=1; n<limit; n++)
{
result = add_digits(n);
if(result==i)
counter++;
}
printf("\n%d\n", counter-1);
return 0;
}
long add_digits(long n)
{
static long sum = 0;
if (n == 0) {
return 0;
}
sum = n%10 + add_digits(n/10);
return sum;
}
Upvotes: 0
Views: 710
Reputation: 2191
As others pointed out that pow()
call is the key for your problem. It operates on double
's, returning double
, then you probably put the result in a 32bit integer on your platform. 10^10 just does not fit in 32 bits, and that's one part of your problem. The other part is accuracy: If you just make an int equal to a double, then you will likely encounter something like in this question.
So the simplest thing to do here is for one probably just raising 10 to the requested power "by hand" (a simple for
loop), and using 64 bit types as others suggested to be able to represent more digits.
(Note that although you might try to round the result of pow proper, with large numbers it may lose accuracy on the lowest digits and you again would get to the point that you run your loop incorrect times)
Upvotes: 0
Reputation: 234785
Without giving your code any more than a cursory examination, it must be due to hitting the limit of int
or long
, which are probably 32 bits on your platform. (And the maximum size of a 32 bit number is 10 digits long).
Why not use int64_t
which is always 64 bit, and standard since C99? pow
may well be giving you problems too; but you could build a quick and dirty multiply by 10 a few times to eliminate that possibility.
Upvotes: 3
Reputation: 166
The size of ints and longs depend on what you are programming it for so you can't be certain how many bits they use (they both could be 32 bit). You can try and use the library inttypes.h which lets you use int64_t. This way you know for sure your variable is 64bit and should be plenty big enough. Good luck!
Upvotes: 2