Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Check the additive persistence of a given number

C++ Math: Exercise-2 with Solution

Write a C++ program to check the additive persistence of a given number.

Additive Persistence
Consider the process of taking a number, adding its digits, then adding the digits of the number derived from it, etc., until the remaining number has only one digit. The number of additions required to obtain a single digit from a number n is called the additive persistence of n, and the digit obtained is called the digital root of n.
For example, the sequence obtained from the starting number 9876 is (9876, 30, 3), so 9876 has an additive persistence of 2 and a digital root of 3. The additive persistences of the first few positive integers are 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, ... (OEIS A031286). The smallest numbers of additive persistence n for n=0, 1, ... are 0, 10, 19, 199, 19999999999999999999999, ... (OEIS A006050).
Source: https://mathworld.wolfram.com/

Sample Solution:

C++ Code :

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int AdditivePersistence(int num) {

	int ctr = 0;

	if (num < 10)
	{
		return 0;
	}

	stringstream convert;
	convert << num;
	string y = convert.str();
	int total_num, n;
	
	do
	{
		total_num = 0;
		ctr++; 

		for (int x = 0; x < y.length(); x++)
		{
			n = int(y[x]) - 48;
			total_num += n;
		}

		stringstream convert;
		convert << total_num;
		y = convert.str();
	} while (total_num >= 10);
	
	return ctr;
}

int main() {

	cout << "Additive persistence of 4 is " << AdditivePersistence(4) << endl;
	cout << "\nAdditive persistence of 125 is " << AdditivePersistence(125) << endl;
	cout << "\nAdditive persistence of 5489 is " << AdditivePersistence(5489) << endl;
	cout << "\nAdditive persistence of 36024 is " << AdditivePersistence(36024) << endl;
	return 0;
}

Sample Output:

Additive persistence of 4 is 0

Additive persistence of 125 is 1

Additive persistence of 5489 is 2

Additive persistence of 36024 is 2

Flowchart:

Flowchart: Check the additive persistence of a given number.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to check whether a given number is a power of two or not.
Next: Write a C++ program to reverse the digits of a given integer.

What is the difficulty level of this exercise?