จำนวนปิรามิดห้าเหลี่ยมเท่ากับจำนวนสิ่งของในปิรามิดฐานห้าเหลี่ยม ดูตัวเลขห้าเหลี่ยมด้านล่าง

ผลรวมของตัวเลขห้าเหลี่ยมจนถึง 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 Pentagonal Pyramidal Number ซึ่งก็คือ 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 เป็นต้น เราหวังว่าคุณจะพบว่าบทความนี้มีประโยชน์