计算数字根,有更好的方法吗?

Ibn*_*eed 2 java math

这就是我计算整数的数字根的方法.


import acm.program.*;

public class Problem7 extends ConsoleProgram
{
    public void run()
    {
        println("This program calculates the digital root of an interger.");

        int num = readInt("Enter the number: ");
        int sum = 0;
        while (true)
        {
            if (num > 0)
            {
                int dsum = num % 10;
                num /= 10;
                sum += dsum;
            }
            else if (sum > 9)
            {
                int dsum = sum % 10;
                sum /= 10;
                sum += dsum;

            } else if (sum <= 9 ) break;
        }
        println("Digital Root is: " + sum);
    }
Run Code Online (Sandbox Code Playgroud)

该程序工作正常.

是否有更好/更短的方法来计算数字的数字根.?


编辑/补充:这是通过使用Tyler的答案实现上述问题,它也有效:


import acm.program.*;

public class Problem7 extends ConsoleProgram
{
    public void run()
    {
        println("This program calculates the digital root of an interger.");

        int num = readInt("Enter the number: ");
        println("Digital Root of " + num + " is: " + (1 + (num - 1) % 9));
    }
}
Run Code Online (Sandbox Code Playgroud)

Tyl*_*ler 15

#include <stdio.h>

int main(void)
{
   int number;
   scanf("%d", &number);

   printf("The digital root of %d is %d.", number, (1 + (number - 1) % 9));
}
Run Code Online (Sandbox Code Playgroud)

如果我找不到拉曼的公式,我就会写这个程序......:

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    int c;
    int number = 0;
    while ((c = getchar()) != EOF)
    {
        if (isdigit(c))
            number += (c - '0');
    }
    if (number <= 9)
    {
        printf("The digital root is %d\n", number);
    }
    else
    {
        printf("%d", number);
    }

}
Run Code Online (Sandbox Code Playgroud)

在编译之后,要运行它,基本上你只需将它们链接在一起.我相信四是整数你可能需要的最多.

$ echo 829382938 | ./digitalroot | ./digitalroot | ./digitalroot | ./digitalroot
Run Code Online (Sandbox Code Playgroud)

  • 该公式位于页面底部:http://en.wikipedia.org/wiki/Digital_root这非常棒. (3认同)
  • 编写实际代码时,应始终使用完善的算法.无需重新发明轮子.然而,对于家庭作业,他们可能试图教你如何工作,所以你应该尝试自己计算算法.通过这种方式,您将学到更多知识,并能够更加欣赏Ramans公式中所包含的聪明才智. (2认同)