题意:求出所给数字的数字根。 数字根:一个数字各个数位的数字和,如果大于10,就重复该过程,如12345的数字根是6,先1+2+3+4+5=15,再1+5=6。 解题思路:利用数字根公式num = (n-1)%9+1;下面给出这个公式的数学证明:1、一个数字和他各个数位的数字和模九同余。以12345为例,可以写成1*9999+2*999+3*99+4*9+1+2+3+4+5,所以结论显然成立,因为任意一个自然数都可以完成上述拆分。2、然后在数学情况下,mod9的完全剩余系是0~8,而题目要求应该是1~9,所以需要先-1,取模后再+1。(真的感觉数学竞赛没白学~o(* ̄▽ ̄*)ブ) 本题坑点:首先这个数字可能非常大,用longlong都搞不定,所以要用字符串。其次如果不知道这个公式直接模拟的话可能会TLE,不过没试过……大家可以试试再告诉我~
Digital Roots |
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
Total Submission(s): 1445 Accepted Submission(s): 580 |
|
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.
|
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 24390
|
Sample Output 63 |
#include <iostream>
using namespace std;
int main()
{
int num,i;
string a;
while(cin>>a && a[0]!= '0')
{
num = 0;
for(i=0;i<a.size();i++)
{
num += a[i]-'0';
}
/*do{
num = 0;
while(n)
{
num += (n%10);
n /=10;
}
n = num;
}while(num>=10);*/
if(num>9)
cout << (num-1)%9 + 1 <<endl;
else
cout<<num<<endl;
}
//cout << "Hello world!" << endl;
return 0;
}