11332 - Summing Digits

本博客介绍了一个算法,用于确定一个正整数在不断求各位数字之和后的最终重复一位数。通过实例解释了计算过程,并提供了C语言实现代码。

For a positive integer n, let f(n) denote the sum of the digits of n when represented in base 10. It is easy to see that the sequence of numbers n, f(n), f(f(n)), f(f(f(n))), ... eventually becomes a single digit number 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 = 47
f(f(n)) = 4+7 = 11
f(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.

对一个正整数n, f(n) 表示n 以十进位表示时所有位数的和。显而易见地,数列n, f(n), f(f(n)), f(f(f(n))), ...一直重覆下去最后会变成一个一位数的整数。这个一位数字以 g(n) 表示。

例如,若 n = 1234567892,则:

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

f(f(n)) = 4+7 = 11

f(f(f(n))) = 1+1 = 2

因此, g(1234567892) = 2。

Sample input

2
11
47
1234567892
0

Output for sample input

2
2
2
2

解题思路:把给定的数拆开来,相加如果大于9,再拆再加直到和小于10为止


#include<stdio.h>
long f(long n)
{long sum=0,a;
while(n){
         sum+=n%10;
         n/=10;
         }
if(sum>=10)a=f(sum);
else a=sum;
return a;
}
int main()
{long n;
while(scanf("%ld",&n)!=EOF){
                            if(n==0)break;
                            printf("%ld\n",f(n));
                            }
return 0;
}

 

转载于:https://www.cnblogs.com/EVA00/archive/2013/02/19/2917645.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值