Back to the Training Home
Lesson: 25
Problem: 1551
Title: Digital Roots
Difficulty Level: 1.0
Date: FEB 27, 2009
Site: http://acm.tju.edu.cn/toj/
Very easy and very good for very beginners. You are given an integer,
you have to find digital root of this number. Lets given integer is 1234.
Sum up all digits of 1234, which is 1+2+3+4 = 10.
Repeat again, 10 = 1+0 = 1. We stop here, because 1 is a single digit number.
So digital root of 1234 is 1.
Solution:
#include<stdio.h>
#include<string.h>
char input[1000];
int getSum() {
int i, sum = 0;
for(i = 0; input[i]; i++) {
sum += input[i] - '0';
}
return sum;
}
int getRoot(int n) {
int sum;
while(n > 9) {
sum = 0;
while(n) {
sum += n%10;
n/=10;
}
n = sum;
}
return n;
}
int main() {
int n;
while(gets(input)) {
if(!strcmp(input,"0")) break;
n = getSum();
printf("%d\n",getRoot(n));
}
return 0;
}
Back to the Training Home