
Sponsored
Sponsored
The iterative approach involves summing the digits of the number repeatedly until the sum becomes a single-digit number. This is a straightforward approach and uses basic loops to repeatedly process the digits of the number.
1#include <stdio.h>
2
3int addDigits(int num) {
4 while (num >= 10) {
5 int sum = 0;
6 while (num > 0) {
7 sum += num % 10;
8 num /= 10;
9 }
10 num = sum;
11 }
12 return num;
13}
14
15int main() {
16 int num = 38;
17 printf("%d\n", addDigits(num));
18 return 0;
19}The function addDigits takes an integer which it divides into its individual digits by taking the modulo and integer division operations. It sums these digits and repeats the process until the result is a single digit.
The mathematical approach leverages a known number theory result related to digit root which can be deduced using modulo 9 arithmetic. The result for the repeated digit sum is equivalent to the number modulo 9, except that when the number is zero it should remain zero.
1def add_digits(
Python leverages the modulo operation directly, taking advantage of the digit root principle for fast computation.