使用 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 等)中編寫相同的程式碼。希望本文對你有所幫助。

更新於: 2021 年 11 月 26 日

137 次瀏覽

開啟你的職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.