我们被赋予正整数变量“num”和“x”。任务是递归计算 num ^ x,然后将所得数字的数字相加,直到达到个位数为止,所得的个位数将作为输出。
让我们看看各种输入输出场景为此 -输入 − int num = 2345, int x = 3
输出 − n 中数字的递归和^x,其中 n 和 x 非常大: 8
解释− 我们给出正整数值 num 和 x,值为 2345,幂为 3。首先,计算 2345 ^ 3 即 12,895,213,625。现在,我们将这些数字相加,即 1 + 2 + 8 + 9 + 5 + 2 + 1 + 3 + 6 + 2 + 5,即 44。现在我们将添加 4 + 4,即 8。由于我们已经达到了个位数,因此,输出为 8。
输入− int num = 3, int x = 3
输出 − 数字的递归和在 n^x 中,其中 n 和 x 非常大: 9
解释− 我们给出正整数值 num 和 x,值为 3,幂为 3 . 首先计算3 ^ 3,即9。由于我们已经得到了个位数,因此输出为9,不需要进一步计算。
下面程序中使用的方法如下输入整数变量 num 和 x,并将数据传递给函数 recursive_digit(num, x) 进行进一步处理。
在函数 recursive_digit(num, x) 内将变量 'total' 声明为 long 并将其设置为调用函数total_digits(num),该函数将返回作为参数传递的数字的数字和。
将变量声明为 long 类型的 temp 并使用 % 6 的幂设置它
检查 if total = 3 or total = 6 and power > 1,然后返回 9。
else if,power = 1,然后返回 total。
li>else if, power = 0 然后返回 1。
else if, temp - 0 然后返回调用total_digits((long)pow(total , 6))
否则,返回total_digits((long)pow(total, temp))。
函数内部 long total_digits(long num)
检查 if num = 0,然后返回 0。检查 if,num % 9 = 0然后返回 9。
否则,返回 num % 9
示例 h2>#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;}
输出如果我们运行上面的代码,它将生成以下输出
recursive sum of digit in n^x, where n and x are very large are: 1
以上就是递归求n^x的各位数字之和,其中n和x都非常大,使用c++实现的详细内容。
