C++: Digital Root

Bjarne-stroustrup
 

The digital root, X, of a number, n, is calculated:

find X as the sum of the digits of n
find a new X by summing the digits of X, repeating until X has only one digit.

The additive persistence is the number of summations required to obtain the single digit.

The task is to calculate the additive persistence and the digital root of a number, e.g.:

627615 has additive persistence 2 and digital root of 9;
39390 has additive persistence 2 and digital root of 6;
588225 has additive persistence 2 and digital root of 3;
393900588225 has additive persistence 2 and digital root of 9;

The digital root may be calculated in bases other than 10.

// Calculate the Digital Root and Additive Persistance of an Integer - Compiles with gcc4.7
//
// Nigel Galloway. July 23rd., 2012
//
#include <iostream>
#include <cmath>
#include <tuple>

std::tuple<const unsigned long long int,int,int> DigitalRoot(const unsigned long long int digits, const int BASE = 10) {
	int x = SumDigits(digits,BASE);
	int ap = 1;
	while (x >= BASE) {
		x = SumDigits(x,BASE);
		ap++;
	}
	return std::make_tuple(digits,ap,x);
}

int main() {
	const unsigned long long int ip[] = {961038,923594037444,670033,448944221089};
	for (auto i:ip){
		auto res = DigitalRoot(i);
		std::cout << std::get<0>(res) << " has digital root " << std::get<2>(res) << " and additive persistance " << std::get<1>(res) << "\n";
	}
	std::cout << "\n";
	const unsigned long long int hip[] = {0x7e0,0x14e344,0xd60141,0x12343210};
	for (auto i:hip){
		auto res = DigitalRoot(i,16);
		std::cout << std::hex << std::get<0>(res) << " has digital root " << std::get<2>(res) << " and additive persistance " << std::get<1>(res) << "\n";
	}
	return 0;
}
Output:
961038 has digital root 9 and additive persistance 2
923594037444 has digital root 9 and additive persistance 2
670033 has digital root 1 and additive persistance 3
448944221089 has digital root 1 and additive persistance 3

7e0 has digital root 6 and additive persistance 2
14e344 has digital root f and additive persistance 2
d60141 has digital root a and additive persistance 2
12343210 has digital root 1 and additive persistance 2

SOURCE

Content is available under GNU Free Documentation License 1.2.