在 C++ 中尋找 1, 4, 27, 16, 125, 36, 343... 系列的第 n 項的程式
在這個問題中,我們獲得了一個整數 N。任務是在 1, 4, 27, 16, 125, 36, 343... 系列中找到第 n 項。
我們舉個例子來理解這個問題,
輸入
N = 7
輸出
343
解釋
該系列為 1,4, 27, 16, 125, 36, 343…
解決方案思路
一個簡單的解決問題的方法是透過找出該系列的公有項。該系列包含兩個不同的系列,一個是奇數項,另一個是偶數項。如果當前元素索引為偶數,則該元素為其索引的平方。如果當前元素索引為奇數,則該元素為其索引的立方。
說明我們解決方案工作原理的程式,
示例
#include <iostream>
using namespace std;
int findNthTerm(int N) {
if (N % 2 == 0)
return (N*N);
return (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 64
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP