24h購物| | PChome| 登入
2011-12-14 23:04:00| 人氣6,005| 回應0 | 上一篇 | 下一篇

[UVA] 11332 - Summing Digits

推薦 0 收藏 0 轉貼0 訂閱站台

Problem J: Summing Digits

For a positive integer n, let f(n) denote the sum of the digitsof n when represented in base 10. It is easy to see that the sequence ofnumbers n, f(n), f(f(n)), f(f(f(n))), ... eventually becomes a single digitnumber that repeats forever. Let this single digit be denoted g(n).

For example, consider n = 1234567892. Then:

f(n) = 1+2+3+4+5+6+7+8+9+2 = 47f(f(n)) = 4+7 = 11f(f(f(n))) = 1+1 = 2

Therefore, g(1234567892) = 2.

Each line of input contains a single positive integer n at most 2,000,000,000.For each such integer, you are to output a single line containing g(n).Input is terminated by n = 0 which should not be processed.

Sample input

2114712345678920

Output for sample input

2222



#include<stdio.h>
int f(int n) {
    if(n < 10)    return n;
    int sum = 0;
    while(n) {
        sum += n%10;
        n /= 10;
    }
    return f(sum);
}
int main() {
    int n;
    while(scanf("%d", &n) == 1 && n)
        printf("%d\n", f(n));
    return 0;
}

台長: Morris
人氣(6,005) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 10177 - (2/3/4)-D Sqr/Rects/Cubes/Boxes?
此分類上一篇:[UVA] 429 - Word Transformation

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文