add Digits Algorithm

The Add Digits Algorithm, also known as the Digital Root algorithm, is a mathematical technique that aims to reduce a given number to a single-digit value by recursively summing its digits. This is based on the concept that adding the digits of a number repeatedly until a single digit is obtained will yield the same result as the original number modulo 9. In essence, the algorithm calculates the digital root of an input number, which is the single-digit value remaining after the iterative process of summing the digits. The Add Digits Algorithm has applications in various fields, including number theory, computer science, and numerology. To implement the Add Digits Algorithm, one can follow these steps: First, take the input number and break it down into its individual digits. Next, sum the digits together to form a new number. If the new number is still more than one digit long, repeat the process until a single-digit number is obtained. Alternatively, a more efficient approach can be achieved using a mathematical formula: Digital Root(n) = 1 + ((n - 1) % 9), where n is the input number. This formula eliminates the need for iterative calculations and offers a faster solution. The Add Digits Algorithm has been used in various contexts, from designing algorithms for computer systems to analyzing patterns in number sequences and even exploring mystical properties in numerology.
/**
 * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
 *
 * For example:
 *
 * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
 *
 * Follow up:
 * Could you do it without any loop/recursion in O(1) runtime?
 *
 * solution approach:
 * Look at the pattern which emerges when we sum the values and eventually reduce it to single digit. By observing carefully, we will see a pattern.
 *
 * This is calculating digital root of a number (https://en.wikipedia.org/wiki/Digital_root)
 * The formula is:
 * dr(n) = 0 if n = 0,
 * 		   9 if n != 0 and  (n % 9 == 0)
 * 		   n % 9
 *
 */

#include <iostream>


int sumDigits( int num ) {
	if ( num == 0 ) {
		return 0;
	} else if ( num % 9 == 0 ) {
		return 9;
	}
	return num % 9;
}

int main() {
	int n;
	std::cout << "Enter a number:";
	std::cin >> n;
	std::cout << "Digital root of " << n << " is :" << sumDigits(n) << std::endl;
	return 0;
}

LANGUAGE:

DARK MODE: