C++ 中 n^x 的遞迴數字和,其中 n 和 x 非常大


給定正整數變數 ‘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’ 為長整型,並將其設定為呼叫函式 total_digits(num),該函式將返回作為引數傳遞的數字的數字和。

    • 宣告變數 temp 為長整型,並將其設定為 power % 6。

    • 檢查 IF total = 3 或 total = 6 且 power > 1,則返回 9。

    • 否則如果 power = 1,則返回 total。

    • 否則如果 power = 0,則返回 1。

    • 否則如果 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。

示例

#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

更新於:2021年11月2日

瀏覽量:135

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.