在 C++ 中找出數列 3, 13, 42, 108, 235... 的第 n 項
在這個問題中,給定一個數字 n。我們的任務是找出數列 3, 13, 42, 108, 235... 的第 n 項
我們以一個例子來理解這個問題:
Input : 5 Output : 235
解決方案方法
該數列可以表示為前 n 個自然數的立方和。其公式為 (n*(n+1)/2)2。此外,如果在其基礎上加 2*,即可得到所需數列。
該數列的求和公式為 (n*(n+1)/2)2+2*n。
對於 n = 5,根據公式求和為
(5 * (5 + 1 ) / 2)) ^ 2 + 2*5
= (5 * 6 / 2) ^ 2 + 10
= (15) ^ 2 + 10
= 225 + 10
= 235
示例
程式,展示我們解決方案的工作原理
#include <iostream>
using namespace std;
int findNthTerm(int N)
{
return ((N * (N + 1) / 2)*(N * (N + 1) / 2) ) + 2 * N;
}
int main()
{
int N = 5;
cout<<"The Nth term fo the series n is "<<findNthTerm(N);
return 0;
}輸出
The Nth term fo the series n is 235
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP