Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การหาเลข Pentagonal Pyramidal ด้วย C++

เลข Pentagonal Pyramidal (พีระมิดห้าเหลี่ยม) เท่ากับจำนวนรายการในพีระมิดฐานห้าเหลี่ยม ดูเลข Pentagonal ด้านล่างนี้

การหาเลข Pentagonal Pyramidal ด้วย C++

ผลรวมของเลข Pentagonal จนถึง N เท่ากับเลข Pentagonal Pyramidal ตัวที่ N ในบทความนี้ เราจะอภิปรายการหาเลข Pentagonal Pyramidal ตัวที่ N ตัวอย่างเช่น:

Input : N = 4
Output : 40
คำอธิบาย : ผลรวมของเลข Pentagonal 4 ตัวแรก 1, 5, 12, 22 คือ 40

Input : N = 6
Output : 126
คำอธิบาย : ผลรวมของเลข Pentagonal 6 ตัวแรก 1, 5, 12, 22, 35, 51 คือ 126

วิธีการแก้ปัญหา

วิธีง่าย (Simple Approach)

ตามตัวอย่าง วิธีที่ง่ายที่สุดคือ วนลูปตั้งแต่ 1 ถึง N และบวกเลข Pentagonal ไปเรื่อยๆ เลข Pentagonal สามารถหาได้จากสูตร (3 × n² - n) / 2

เช่น สำหรับ n = 2, เลข Pentagonal = (3 × 2² - 2)/2 = 5

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N = 6, SUM = 0;
    // วนลูปจาก 1 ถึง N
    for (int i = 1; i <= N; i++) {
        // คำนวณเลข Pentagonal ตัวที่ i
        // และบวกเข้าไปใน SUM
        SUM = SUM + (3 * i * i - i) / 2;
    }
    cout << "Nth Pentagonal Pyramidal Number: " << SUM << endl;
    return 0;
}

ผลลัพธ์

Nth Pentagonal Pyramidal Number: 126

วิธีที่มีประสิทธิภาพ (Efficient Approach)

โปรแกรมสามารถมีประสิทธิภาพได้โดยใช้สูตรเพื่อหาเลข Pentagonal Pyramidal ตัวที่ N ซึ่งคือ n² × (n + 1) / 2

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N = 6, result;
    // คำนวณเลข Pentagonal Pyramidal ตัวที่ N ด้วยสูตร
    result = N * N * (N + 1) / 2;
    cout << "Nth Pentagonal Pyramidal Number: " << result << endl;
    return 0;
}

ผลลัพธ์

Nth Pentagonal Pyramidal Number: 126

สรุป

ในบทความนี้ เราอภิปรายปัญหาการหาเลข Pentagonal Pyramidal ตัวที่ N เราอภิปรายสองวิธีในการแก้ปัญหานี้: วนลูปจนถึงตัวที่ N และใช้สูตร เรายังอภิปรายโปรแกรม C++ เพื่อแก้ปัญหานี้ เราสามารถเขียนโค้ดเดียวกันในภาษาโปรแกรมอื่นๆ เช่น C, Java, Python ฯลฯ ได้ เราหวังว่าบทความนี้จะเป็นประโยชน์