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


這裡,我們來看如何獲取最後兩位數字。N 個階乘之和的個位數和十位數。因此,如果 N = 4,則為 1! + 2! + 3! + 4! = 33。因此,個位數是 3,十位數是 3。結果將是 33。

如果我們清楚地看到,那麼當 N > 5 的階乘時,個位數為 0,因此 5 之後,它不會改變個位數。而且,在 N > 10 之後,十位數將保持為 0。對於 N = 10 及更大值,將變為 00。我們可以繪製一張從 1 到 10 的階乘數字圖表。

我們可以使用以下步驟解決此問題 -

  • 如果 n 的值小於 10,則 (1! + 2! + … + n!) mod 10
  • 否則,當 n 的值大於或等於 10 時,則 (1! + 2! + … + 10!) mod 10 = 13

示例

#include<iostream>
#include<cmath>
using namespace std;
int getTenAndUnitPlace(long long N) {
   if (N <= 10) {
      long long ans = 0, factorial = 1;
      for (int i = 1; i <= N; i++) {
         factorial = factorial * i;
         ans += factorial;
      }
      return ans % 100;
   }
   return 13;
}
int main() {
   for(long long i = 1; i<15; i++){
      cout << "Ten and Unit place value of sum of factorials when N = "<<i<<" is: " <<getTenAndUnitPlace(i) << endl;
   }
}

輸出

Ten and Unit place value of sum of factorials when N = 1 is: 1
Ten and Unit place value of sum of factorials when N = 2 is: 3
Ten and Unit place value of sum of factorials when N = 3 is: 9
Ten and Unit place value of sum of factorials when N = 4 is: 33
Ten and Unit place value of sum of factorials when N = 5 is: 53
Ten and Unit place value of sum of factorials when N = 6 is: 73
Ten and Unit place value of sum of factorials when N = 7 is: 13
Ten and Unit place value of sum of factorials when N = 8 is: 33
Ten and Unit place value of sum of factorials when N = 9 is: 13
Ten and Unit place value of sum of factorials when N = 10 is: 13
Ten and Unit place value of sum of factorials when N = 11 is: 13
Ten and Unit place value of sum of factorials when N = 12 is: 13
Ten and Unit place value of sum of factorials when N = 13 is: 13
Ten and Unit place value of sum of factorials when N = 14 is: 13

更新於:2019 年 10 月 30 日

122 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.