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

โปรแกรม C/C++ สำหรับ Triangular Matchstick Number

ที่นี่เราจะดูวิธานับจำนวนไม้ขีดไฟ (matchsticks) ที่ต้องใช้สร้างรูปพีระมิด ฐานของพีระมิดกำหนดให้ ฐาน 1 ใช้ 3 ไม้ ฐาน 2 ใช้ 9 ไม้ ฐาน 3 ใช้ 18 ไม้

โปรแกรม C/C++ สำหรับ Triangular Matchstick Number

สูตรที่ใช้:

โปรแกรม C/C++ สำหรับ Triangular Matchstick Number

สูตร: 3 × n × (n + 1) / 2

ตัวอย่างโค้ด (C++)

#include <iostream>
using namespace std;

int main() {
    int x;
    cout << "Enter the size of the base: ";
    cin >> x;
    int count = 3 * x * (x + 1) / 2;
    cout << "Required Matchsticks: " << count;
}

ผลลัพธ์

Enter the size of the base: 5
Required Matchsticks: 45