九餘數定理

Digital Roots

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
 

題意分析:數根的定義:將一個數的每位數相加得到一個新的數,如果該數爲一位數,該新數即是數根;否則重複開頭的步驟。例如:28945 -> 2+8+9+4+5=28 -> 2+8+10 -> 1+0 = 1;所以1即是28945的數根。

解題思路:當然,直接按題目的字面意思做也能AC。這裏我只是想介紹一下九餘數定理。
我麼們知道,不管是什麼數,數根一定是0~9其中的一個,因爲不會有正數各位之和爲0。

證明:
假設,數d的根爲d%9( 暫時不取0,整除時取9)
當d < 10時,1~9這9個數肯定成立;
當d >= 10時,d的根爲d%9 = (d-1)%9+1,即d的前一個數的數根加1.

得證.

源代碼如下:
<strong>#include<cstdio>
int main(void)
{
	while(1)
	{
	    int num=0;
        char ch;
		while(scanf("%c",&ch) && ch!='\n')  num += ch-'0';
		if(!num) return 0;
		else if(num%9 == 0) puts("9");
		else printf("%d\n",num%9);
	}
	
	return 0;
}</strong>



類似的題:
Eddy's digital Roots 只不過這裏變成求Nn的數根

源代碼如下:
<span style="font-size:18px;">#include<cstdio>

int main(void)
{
    int n,i,ans;
    while(scanf("%d",&n),n)
    {
        ans = 1;
        for(i = 0; i < n; i++)
            ans = ans*n%9;
        if(!ans) puts("9");
        else printf("%d\n",ans);
    }

    return 0;
}</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章