Digital Roots 求一个数的数字根

Dear 丶 2022-06-08 00:59 294阅读 0赞

The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.

For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

Input

The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.

Output

For each integer in the input, output its digital root on a separate line of the output.

Sample Input

24
39
0

Sample Output

6
3

//记录一下小方法 合九法:一个数的数字根等于这个数模9,也等于各个位所有数之和模9。

  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <string.h>
  4. int main()
  5. {
  6. int sum;
  7. char s[1005] ;
  8. while(scanf("%s",s))
  9. {
  10. if(strlen(s)==1 && s[0]=='0') break;
  11. sum=0;
  12. for(int i=0;i<strlen(s);i++)
  13. {
  14. sum+=s[i]-'0';
  15. }
  16. printf("%d\n",sum%9?sum%9:9);
  17. }
  18. return 0;
  19. }

发表评论

表情:
评论列表 (有 0 条评论,294人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C语言 数字乘积

    任务描述 从终端输入正整数,求该整数的数字乘积根。 功能要求 ①本程序要求可以连续求得多个整数的数字乘积根,直到用户输入数字0时,退出程序。 ②在主函数中输入正

    相关 补齐函数

    输入n个正整数(输入格式中第一行为整数个数n,后续行为n个整数),输出各个数的数根。数根的定义:对于一个正整数n,我们将它的各个位相加得到一个新的数字,如果这个数字是一位数,我