Home  >  Article  >  Backend Development  >  Recursively sum the sum of the digits of a number formed by repeated additions, implemented in C++

Recursively sum the sum of the digits of a number formed by repeated additions, implemented in C++

王林
王林forward
2023-09-02 14:01:06765browse

Recursively sum the sum of the digits of a number formed by repeated additions, implemented in C++

Given two integers "number" and "repeat" as input. The goal is to calculate the numerical sum of an input number repeated a "repeat" number of times until the sum becomes a single number. Continue in this way until the sum of the numbers obtained becomes a single digit. If the input number is 123 and repeat=2 then the sum of 123123 will be 1 2 3 1 2 3=12 This is not a single digit. Now the sum of the digits of 12 is 1 2 = 3. The output will be 3

Let’s look at various input and output scenarios for this

Input− number=32 Repeat=3

Output− The recursive sum of the numbers formed by repeated appending is: 6

Explanation − The sum of the numbers of 323232 is 3 2 3 2 3 2=15, and the sum of the digits of 15 is 1 5=6. 6 is a single digit, so the output will be 6.

Input− number=81 Repeat=4

Output−The recursive digital sum of the numbers formed by repeated appending is: 9

Explanation - The sum of the digits of 81818181 is 1 8 1 8 1 8 1 8=36, and the sum of the digits of 36 is 3 6=9. 9 is a single digit, so the output will be 9.

The method used in the following program is as follows

  • Declare two integer type variables such as number and repeat. Pass the data to the function as Recursive_Sum(number, Repeat).

  • Inside the function as Recursive_Sum(int number, int Repeat)

    • Declare an integer variable as total and use repeat * sum(number ) sets it;

    • Returns a call to the function as sum(total) .

  • Inside the function as sum (int number)

    • Check if the IF number is 0 and return 0.

    • Checks if the IF number % 9 is 0 and returns 9.

    • ELSE, return number % 9

  • Print the result.

Example

#include <bits/stdc++.h>
using namespace std;
int sum(int number){
   if(number == 0){
      return 0;
   }
   if(number % 9 == 0){
      return 9;
   }
   else{
      return number % 9;
   }
}
int Recursive_Sum(int number, int repeat){
   int total = repeat * sum(number);
   return sum(total);
}
int main(){
   int number = 12;
   int repeat = 4;
   cout<<"Recursive sum of digits of a number formed by repeated appends is: "<<Recursive_Sum(number, repeat);
   return 0;
}

Output

If we run the above code it will generate the following output

Recursive sum of digits of a number formed by repeated appends is: 3

The above is the detailed content of Recursively sum the sum of the digits of a number formed by repeated additions, implemented in C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete