使用 C++ 查詢 N 個階乘之和的個位數。


在這裡,我們將瞭解如何獲取 N 個階乘之和的個位數。所以如果 N 是 3,那麼在得到和之後,我們將得到 1! + 2! + 3! = 9,這將是結果,對於 N = 4,它將是 1! + 2! + 3! + 4! = 33。所以個位數是 3。如果我們仔細觀察,那麼當 N > 5 時,階乘的個位數為 0,所以 5 之後,它將不會導致個位數發生變化。對於 N = 4 及以上,它將是 3。我們可以為個位數製作一個圖表,這將在程式中使用。

示例

#include<iostream>
#include<cmath>
using namespace std;
double getUnitPlace(int n) {
   int placeVal[5] = {-1, 1, 3, 9, 3};
   if(n > 4){
      n = 4;
   }
   return placeVal[n];
}
int main() {
   for(int i = 1; i<10; i++){
      cout << "Unit place value of sum of factorials when N = "<<i<<" is: " << getUnitPlace(i) << endl;
   }
}

輸出

Unit place value of sum of factorials when N = 1 is: 1
Unit place value of sum of factorials when N = 2 is: 3
Unit place value of sum of factorials when N = 3 is: 9
Unit place value of sum of factorials when N = 4 is: 3
Unit place value of sum of factorials when N = 5 is: 3
Unit place value of sum of factorials when N = 6 is: 3
Unit place value of sum of factorials when N = 7 is: 3
Unit place value of sum of factorials when N = 8 is: 3
Unit place value of sum of factorials when N = 9 is: 3

更新於: 2019 年 10 月 30 日

139 次檢視

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告