Skip to content

Instantly share code, notes, and snippets.

@EmilHernvall
Created May 3, 2011 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmilHernvall/953766 to your computer and use it in GitHub Desktop.
Save EmilHernvall/953766 to your computer and use it in GitHub Desktop.
Simple mathematical approach for summing the digits in a number
#include <stdio.h>
#include <math.h>
/*
The algorithm is:
d_i = (c mod 10^(i+1)) / 10^i
S = sum_{i=0}^{floor(log_10(c))+1} d_i = sum_{i=0}^{floor(log_10(c))+1} (c mod 10^(i+1)) / 10^i
Where c is the number in question, d_i is the digit at position i counted from the least significant digit
and S is the sum of the digits in the number.
*/
int main(void)
{
int c = 1000;
printf("The number is %d.\n", c);
int s = 0;
/*
// Special case for 3 digits:
s += (c % 10) / 1;
s += (c % 100) / 10;
s += (c % 1000) / 100;
*/
printf("%f\n", log(c));
// General case for n digits
int i;
for (i = 0; i < (int)(log(c) / log(10)) + 1; i++) {
s += (c % (int)pow(10, i + 1)) / (int)pow(10, i);
}
printf("The sum of the digits is %d.\n", s);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment