使用 C++ 查找五角锥数
五角锥数等于五角锥底部的物品数量。看看下方的几个五角数。

N までの五角数和等于第 N 个五角锥数。本文将讨论寻找第 N 个五角锥数,比如
Input : N = 4 Output : 40 Explanation : Sum of first four pentagonal numbers 1, 5, 12, 22 is 40. Input : N = 6 Output : 126 Explanation : Sum of first four pentagonal numbers 1, 5, 12, 22, 35, 51 is 40.
求解方法
简单方法
根据示例,最简单的方法是:遍历从 1 到 N 的数字,并不断添加五角数。五角数可以通过公式 (3 * n2 - n) / 2 来计算
例如,对于 n = 2,五角数 = (3 * 22 - 2)/2 = 5
示例
#include <bits/stdc++.h>
using namespace std;
int main () {
int N = 6, SUM = 0;
// traversing from number 1 to N.
for (int i = 1; i <= N; i++) {
// Calculating ith pentagonal number
// and adding to the SUM.
SUM = SUM + (3 * i * i - i) / 2;
}
cout <<"Nth Pentagonal Pyramidal Number: "<< SUM << endl;
return 0;
}输出
Nth Pentagonal Pyramidal Number: 126
有效方法
可以使用计算第 N 个五角锥数的公式 n2 * (n + 1) / 2,提高程序的效率。
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
int N = 6, result;
// calculating Nth pentagonal pyramidal number by formula.
result = N * N * (N + 1) / 2;
cout <<"Nth Pentagonal Pyramidal Number: " << result << endl;
return 0;
}输出
Nth Pentagonal Pyramidal Number: 126
结论
本文讨论了找到第 N 个五角锥数的问题。讨论了两种解决此问题的方法:遍历到第 N 个数字和使用公式。还讨论了用于解决此问题的 C++ 程序。我们可以在其他编程语言(例如 C、Java、Python 等)中编写相同的代码。希望本文对你有所帮助。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP