Home > Article > Backend Development > Recursively find the sum of the digits of n^x, where n and x are both very large, implemented using C++
We are given positive integer variables "num" and "x". The task is to recursively calculate num^x and then add the digits of the resulting numbers until it reaches single digits, the resulting single digits will be given as output.
Input − int num = 2345, int x = 3
Output − The recursive sum^x of numbers in n, where n and x are very large: 8
Explanation− We are given the positive integer values num and x, with the value 2345, The power is 3. First, calculate 2345^3 which is 12,895,213,625. Now, let's add these numbers together, which is 1 2 8 9 5 2 1 3 6 2 5, which is 44. Now we're going to add 4 4, which is eight. Since we have reached single digits, the output is 8.
Input− int num = 3, int x = 3
Output − The recursive sum of numbers in n^x, where n and x is very large: 9
Explanation− We are given positive integer values num and x with value 3 and power 3. First calculate 3^3, which is 9. Since we already got the single digits, the output is 9 and no further calculations are needed.
Input the integer variables num and x and pass the data to the function Recursive_Digit(num, x) for further processing.
Declare the variable 'total' as long and set it to call the function total_digits( num), this function returns the numeric sum of the numbers passed as arguments.
Declare the variable as temp of long type and set it using % power of 6
Check IF Total = 3 OR Total = 6 AND power > 1, then returns 9.
ELSE IF, power = 1, then returns Total.
ELSE IF, power = 0 then returns 1.
ELSE IF, temp - 0 and then return to call total_digits((long)pow(total, 6))
Otherwise, return total_digits( (long)pow(total, temp)).
Internal function long Total_digits(long num)
Checks IF num = 0, then returns 0. Check IF, num % 9 = 0 and return 9.
Otherwise, return num % 9
#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){ return total; } else if (power == 0){ return 1; } else if (temp == 0){ return total_digits((long)pow(total, 6)); } else{ return total_digits((long)pow(total, temp)); } } 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; }H2>OutputIf 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
The above is the detailed content of Recursively find the sum of the digits of n^x, where n and x are both very large, implemented using C++. For more information, please follow other related articles on the PHP Chinese website!