Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for digit summing?

I'm searching for an algorithm for Digit summing. Let me outline the basic principle:

Say you have a number: 18268.

1 + 8 + 2 + 6 + 8 = 25

2 + 5 = 7

And 7 is our final number. It's basically adding each number of the whole number until we get down to a single (also known as a 'core') digit. It's often used by numerologists.

I'm searching for an algorithm (doesn't have to be language in-specific) for this. I have searched Google for the last hour with terms such as digit sum algorithm and whatnot but got no suitable results.

like image 324
Joe Avatar asked Apr 21 '10 22:04

Joe


4 Answers

Because 10-1=9, a little number theory will tell you that the final answer is just n mod 9. Here's code:

ans = n%9;
if(ans==0 && n>0) ans=9; 
return ans;

Example: 18268%9 is 7. (Also see: Casting out nines.)

like image 135
ShreevatsaR Avatar answered Nov 14 '22 04:11

ShreevatsaR


I would try this:

int number = 18268;
int core = number;
int total = 0;

while(core > 10)
{
   total = 0;
   number = core;
   while(number > 0)
   {
      total += number % 10;
      number /= 10;
   }

   core = total;
}
like image 33
Grimmy Avatar answered Nov 14 '22 02:11

Grimmy


Doesn't work with negative numbers, but I don't know how you would handle it anyhow. You can also change f(x) to be iterative:

sum( x ) =
    while ( ( x = f( x ) ) >= 10 );
    return x;

f( x ) = 
    if ( x >= 10 ) return f( x / 10 ) + x % 10
    return x

You can also take advantage of number theory, giving you this f(x):

f( x ) =
    if ( x == 0 ) return 0
    return x % 9
like image 20
Larry Avatar answered Nov 14 '22 02:11

Larry


  1. Mod the whole number by 10.
  2. Add the number to an array.
  3. Add the whole array.
like image 33
Jacob Saylor Avatar answered Nov 14 '22 04:11

Jacob Saylor