在 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