C++程式求解數列1, 4, 15, 72, 420…的第N項
在這個問題中,我們給定一個整數N。我們的任務是建立一個程式來查詢數列1, 4, 15, 72, 420…的第N項。
讓我們舉個例子來理解這個問題:
輸入
N = 4
輸出
72
解決方案方法
解決這個問題的一個簡單方法是使用該數列第N項的公式。為此,我們需要觀察該數列,然後概括出第N項。
該數列可以看作是階乘和一些變數的乘積:
1, 4, 15, 72, 420… 1!*(X1), 2!*(X2), 3!*(X3), 4!*(X4), 5!*(X5)... 1*(1), 2*(2), 6*(5/2), 24*(3), 120*(7/2)...
這裡,乘積數列是:
1, 2, 2.5, 3, 3.5…
It is {(n+2)/2}.所以第N項的公式是
T(N) = ( N! * (N + 2)/ 2 )
程式演示了我們解決方案的工作原理:
示例
#include <iostream>
using namespace std;
int calcFactorial(int N) {
int factorial = 1;
for (int i = 1; i <= N; i++)
factorial = factorial * i;
return factorial;
}
int calcNthTerm(int N) {
return (calcFactorial(N) * (N + 2) / 2);
}
int main() {
int N = 7;
cout<<N<<"th term of the series is "<<calcNthTerm(N);
return 0;
}輸出
7th term of the series is 22680
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP