Algorithm for digit summing?

2019-03-11 05:51发布

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.

8条回答
相关推荐>>
2楼-- · 2019-03-11 06:15

this is from a really long time ago, but the best solution i have for this is:

int digitSum(int num){
    if (num < 10) return num;
    else return (n-1)%9+1;
}

I don't know how much better this is,but it will account for the divisible by 9 numbers easily. Just a cool algorithm.

查看更多
放我归山
3楼-- · 2019-03-11 06:15
public int DigitSum(long n)
  {
     return (int)(1 + (n - 1) % 9);
  }
查看更多
放我归山
4楼-- · 2019-03-11 06:17
    private static int sum(long number) {
    int sum = 0;
    if (number == 0) {
        return 0;
    }
    do {
        int last = (int) (number % 10);
        sum = (sum + last) % 9;
    } while ((number /= 10) > 0);

    return sum == 0 ? 9 : sum;
}
查看更多
别忘想泡老子
5楼-- · 2019-03-11 06:18

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
查看更多
虎瘦雄心在
6楼-- · 2019-03-11 06:18
  1. Mod the whole number by 10.
  2. Add the number to an array.
  3. Add the whole array.
查看更多
淡お忘
7楼-- · 2019-03-11 06:21

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.)

查看更多
登录 后发表回答