# Recursive sum of digit in n^x, where n and x are very large in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

We are given positive integer variables as ‘num’ and ‘x’. The task is to recursively calculate the num ^ x then add the digits of a resultant number till the single digit isn’t achieved and the resultant single digit will be the output.

## Let us see various input output scenarios for this −

Input − int num = 2345, int x = 3

Output − Recursive sum of digit in n^x, where n and x are very large are: 8

Explanation − we are given positive integer values as num and x with the values as 2345 and power as 3. Firstly, calculate 2345 ^ 3 i.e. 12,895,213,625. Now , we will add these digits i.e. 1 + 2 + 8 + 9 + 5 + 2 + 1 + 3 + 6 + 2 + 5 i.e. 44. Now we will add 4 + 4 i.e. 8. Since we have achieved the single digit therefore, output is 8.

Input − int num = 3, int x = 3

Output − Recursive sum of digit in n^x, where n and x are very large are: 9

Explanation − we are given positive integer values as num and x with the values as 3 and power as 3. Firstly, calculate 3 ^ 3 i.e. 9. Since we have achieved the single digit therefore, output is 9 and no further calculation is required.

## Approach used in the below program is as follows

• Input an integer variable as num and x and pass the data to the function Recursive_Digit(num, x) for further processing.

• Inside the function Recursive_Digit(num, x)

• Declare variable ‘total’ as long and set it to call the function total_digits(num) which will return the digit sum of a number passed as an argument.

• Declare variable as temp of type long and set it with power % 6

• Check IF total = 3 OR total = 6 AND power > 1 then return 9.

• ELSE IF, power = 0 then return 1.

• ELSE IF, temp - 0 then return call to total_digits((long)pow(total, 6))

• Inside the function long total_digits(long num)

• Check IF num = 0 then return 0. Check IF, num % 9 = 0 then return 9.

• Else, return num % 9

## Example

#include <bits/stdc++.h>
using namespace std;
long total_digits(long num){
if(num == 0){
return 0;
}
if(num % 9 == 0){
return 9;
}
else{
return num % 9;
}
}
long Recursive_Digit(long num, long power){
long total = total_digits(num);
long temp = power % 6;
if((total == 3 || total == 6) & power > 1){
return 9;
}
else if (power == 1){
}
else if (power == 0){
return 1;
}
else if (temp == 0){
}
else{
}
}
int main(){
int num = 2345;
int x = 98754;
cout<<"Recursive sum of digit in n^x, where n and x are very large are: "<<Recursive_Digit(num, x);
return 0;
}

## Output

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

Recursive sum of digit in n^x, where n and x are very large are: 1
Updated on 02-Nov-2021 06:04:24