Recursive sum of digits of a number formed by repeated appends in C++



Given two integers ‘number’ and ‘repeat’ as input. The goal is to calculate the sum of digits of the input number repeated ‘repeat’ number of times until the sum becomes a single digit. Do this till the obtained number with sum of digits becomes a single digit number. If the input number is 123 and repeat=2 than the sum of digits of 123123 will be 1+2+3+1+2+3=12 which is not a single digit number. Now the sum of digits of 12 is 1+2=3. Output will be 3

Let us see various input output scenarios for this

Input − number=32 repeat=3

Output − Recursive sum of digits of a number formed by repeated appends is: 6

Explanation − Sum of digits of 323232 is 3+2+3+2+3+2=15 and sum of digits of 15 is 1+5=6. 6 is a single digit number so output will be 6.

Input − number=81 repeat=4

Output − Recursive sum of digits of a number formed by repeated appends is: 9

Explanation − Sum of digits of 81818181 is 1+8+1+8+1+8+1+8=36 and sum of digits of 36 is 3+6=9. 9 is a single digit number so output will be 9.

Approach used in the below program is as follows

  • Declare two integer type variables 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 set it with a repeat * sum(number);

    • Return call to the function as sum(total).

  • Inside the function as sum(int number)

    • Check IF number is 0 then return 0.

    • Check IF number % 9 is 0 then return 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

Advertisements