您的位置:首页 > 其它

Digital root------[NWPU][2018寒假作业][通用版]一、热身 [Cloned]M题//求数字根的简便方法

2018-01-22 22:55 393 查看
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的倍数模9为0这种特殊情况,数字根记为9。

n%9?n%9:9;

可以用这个语句代替下面代码中root的计算,更为简便。

#include<stdio.h>
#include<string.h>
//求数字根mod9即可
int main()
{
int n,i;
int root;
char num[10000];
while(1)
{
scanf("%s",num);
if(strlen(num)==1&&num[0]=='0')
{
return 0;
}
for(n=0,i=0;i<strlen(num);i++)
{
n+=num[i]-'0';
}
if(n%9==0)
{
root=9;
}
else
{
root=n%9;
}
printf("%d\n",root);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐