我从数字的根源学到一个很有意思的算法,“合九法”。
合九法即一个数的数字根等于这个数模9,也等于各个位所有数之和模9。
例如:算法是这样的:(num%9?9:num%9);
数字的根源题目是这样的:
Problem Description
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
有一位大佬是这样写的:
#include
#include
int main()
{
char num[1000];
int len,sum,i;
while(scanf("%s",&num)!=EOF)
{
len=strlen(num);
if(len==1 && num[0]=='0') return 0;
for(sum=0,i=0;i
{
sum=sum+num[i]-'0'; //字符串转换成数字-‘0’,数字转换成字符串+‘0’
}
printf("%d
",sum%9?sum%9:9);
}
return 0;
}
我原来是曲解了这道题的含义,我以为是输完数字再计算,直到输入0则输入结束,运行结果输出。其实这道题是输入一个数算出数字的根,直到输入0退出程序。
刚开始学习ACM题目,大有不解,借鉴的多。但会继续学习的!
为什么修改了变量的位置就Compilation
Error了呢:
#include
#include
int main()
{
char num[1000];
while(scanf("%s",&num)!=EOF)
{
int sum=0;
int len=strlen(num);
if(len==1 && num[0]=='0') return 0;
for(int i=0;i
{
sum=sum+num[i]-'0'; //字符串转换成数字-‘0’,数字转换成字符串+‘0’
}
printf("%d
",sum%9?sum%9:9);//合九法;一个数的数字根等于这个数模9,也等于各个位所有数之和模9
}
return 0;
}