A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

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

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

0

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).

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#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;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now