C++ 程式找出 2, 10, 30, 68, 130…這個數列的第 n 項
本題中,給出整型數 N。任務是找出數列 2, 10, 30, 68, 130 中的第 n 項。
我們舉個例子來理解這個問題:
輸入
N = 7
輸出
350
解釋
The series is 2, 10, 30, 68, 130, 222, 350...
解決方案方法
一個簡單的解決方案是找出數列的一般項。這裡,數列的第 N 項是 N^3 + N。這是透過減去當前元素和當前索引得到的。
For i, i = 1, T(1) = 2 = 1 + 1 = 1^3 + 1 i = 2, T(1) = 10 = 8 + 2 = 2^3 + 2 i = 3, T(1) = 30 = 27 + 3 = 3^3 + 2
程式說明我們解決方案的工作原理:
示例
#include <iostream>
using namespace std;
int findNthTerm(int N) {
return ((N*N*N) + N);
}
int main() {
int N = 8;
cout<<"The "<<N<<"th term of the series is "<<findNthTerm(N);
return 0;
}輸出
The 8th term of the series is 520
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP