11332 - Summing Digits
Problem J: Summing Digits
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.
Sample input
2
11
47
1234567892
0
Output for sample input
2
2
2
2
Zachary Friggstad
#include<stdio.h>
int main(){ char c[100]; int i,f,fff,ff,a,bb,ccc,aa,b,cc; while(gets(c)!=EOF) {if(c[0]=='0')
{ break;}
int sum=0; int l=strlen(c); for(i=0;i<l;i++) { sum=sum+c[i]-'0';}
if(sum<10) { printf("%d\n",sum);}
else {f=sum/10;
ff=sum%10;
fff=f+ff;
if(fff<10) { printf("%d\n",fff);}
else {a=fff/10;
bb=fff%10;
ccc=f+ff;
if(ccc<10) { printf("%d\n",ccc);}
else {aa=ccc/10;
b=ccc%10;
cc=aa+b;
if(cc<10) { printf("%d\n",cc);}
}
}
}
}
return 0;}
No comments:
Post a Comment