在 C++ 中計算給定範圍內階乘數


給定一個範圍,從一個變數(假設為 start)儲存的整數值開始,到變數 end 結束,任務是計算給定範圍內可用的階乘數的總數。

什麼是階乘數

一個數的階乘是透過將該數的數字相乘,同時將數字的值遞減 1 來計算的。它用符號“!”表示,例如 0!、1!、2!、3!、5!、……等等。0!和 1!的階乘始終為 1。

I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2
      factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6

例如

Input − start = 5, end = 600
Output − Count of factorial numbers are 3

解釋 - 因為在 5-600 的範圍內有 3 個數字具有階乘數。

Input − start = 1, end = 100
Output − Count of factorial numbers are 5

解釋 - 因為在 5-600 的範圍內有 5 個數字具有階乘數。

下面程式中使用的方案如下

  • 輸入範圍並存儲在變數 start 和 end 中

  • 使用另一個變數“fact”來儲存階乘值,並將其初始化為 1,以及一個臨時變數“i”來增加數字計數。

  • 啟動迴圈,當 fact 小於 start 時,繼續將 fact 與 i 相乘以計算階乘,並且同時繼續增加 i 的值。

  • 啟動另一個迴圈,當 fact 小於等於 end 變數時,繼續增加變數 r 的值,並繼續將 fact 設定為 fact * i,同時繼續增加 i 的值。

  • 現在,返回 r 的值,該值儲存著階乘數的總數。

  • 列印結果。

示例

即時演示

#include <iostream>
using namespace std;
// To count the number of factorials
int factorials(int start, int end){
   // Starting from 1 and find the first factorial number
   // 'fact' greater than or equal to 'start'
   int fact = 1, i = 1;
   while (fact < start){
      fact = fact*i;
      i++;
   }
   // r to count factorial numbers in range start to end
   int r = 0;
   while (fact <= end){
      r++;
      fact = fact*i;
      i++;
   }
   // Return the count of factorials in range
   return r;
}
int main(){
   int start = 5, end = 600;
   cout << "Count of factorial numbers are " << factorials(start, end);
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Count of factorial numbers are 3

更新於:2020 年 5 月 15 日

296 次檢視

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告