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

หาพจน์ที่ N ของอนุกรม 1, 6, 18, 40, 75... ด้วย C++


ภาพรวมปัญหา

หาพจน์ที่ N ของอนุกรม: 1, 6, 18, 40, 75, ...

ตัวอย่าง

อินพุต

N = 4

เอาต์พุต

40

คำอธิบาย

4 × 4 × 5 / 2 = 40

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

สูตรทั่วไป: T(N) = N² × (N + 1) / 2

โค้ดตัวอย่าง

#include <iostream>
using namespace std;

int calcNthTerm(int N) {
    return (N * N * (N + 1)) / 2;
}

int main() {
    int N = 5;
    cout << N << "th term of the series is " << calcNthTerm(N);
    return 0;
}

เอาต์พุต

5th term of the series is 75

สรุป

สูตรพหุนามดีกรี 3 หาร 2 คำนวณ O(1)