C++ 程式查詢數列 1、1、2、6、24… 的第 N 項


在這個問題中,我們給定一個整數 N。我們的任務是建立一個程式,找到數列 1、1、2、6、24、... 的第 N 項。

我們舉一個例子來理解這個問題,

輸入

N = 7

輸出

720

說明

該數列為 − 1、1、2、6、24、120、720

解決方案思路

透過使用數列第 n 項的一般公式來解決此問題是一種簡單的方法。公式為,

第 N 項 = (N−1)!

說明我們解決方案工作原理的程式,

示例

 線上演示

#include <iostream>
using namespace std;
int calcNthTerm(int N) {
   if (N <= 1)
      return 1;
      int factorial = 1;
   for (int i = 1; i < N; i++)
      factorial *= i;
      return factorial;
}
int main() {
   int N = 8;
   cout<<N<<"th term of the series is "<<calcNthTerm(N);
   return 0;
}

輸出

8th term of the series is 5040

更新日期:2021 年 3 月 15 日

460 次觀看

開啟你的職業

完成課程即可獲得認證

開始吧
廣告