码迷,mamicode.com
首页 > 其他好文 > 详细

Digital Roots

时间:2014-11-16 17:16:56      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   for   div   

描述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.

 
输入
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.
输出
For each integer in the input, output its digital root on a separate line of the output.
样例输入
24
39
0
样例输出
6
3

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int sum(int number);
 5 
 6 int main(){
 7     char s[1000];
 8     int i;
 9     int number;
10     
11     while(scanf("%s",&s)!=EOF){
12         
13         if(strcmp(s,"0")==0)
14             break;
15             
16         number=0;
17         for(i=0;s[i]!=\0;i++){
18             number+=(s[i]-0);
19         }
20         
21         while(number>=10){
22             number=sum(number);
23         }
24         
25         printf("%d\n",number);
26     }
27     return 0;
28 }
29 
30 int sum(int number){
31     int result;
32     
33     result=0;
34     while(number){
35         result+=number%10;
36         number/=10;
37     }
38     
39     return result;
40 }

 

 

Digital Roots

标签:style   blog   io   color   ar   os   sp   for   div   

原文地址:http://www.cnblogs.com/zqxLonely/p/4101520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!