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

ผลรวมอนุกรม 2 + (2+4) + (2+4+6) + ... + (2+4+...+2n) ใน C++


ภาพรวมปัญหา

หาผลรวมของอนุกรม: 2 + (2+4) + (2+4+6) + ... + (2+4+...+2n)

ตัวอย่าง

Input: n = 3
Output: 20
Explanation: (2) + (2+4) + (2+4+6) = 2 + 6 + 12 = 20

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

วิธี Nested Loop - O(n²)

for i=1 to n:
    for j=1 to i:
        sum += 2*j

วิธีสูตรคณิตศาสตร์ - O(1)

พจน์ที่ n: aₙ = n² + n

ผลรวม = ⅓ n(n+1)(n+2)

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

#include <iostream>
using namespace std;

int calcSeriesSum(int n) {
    return (n * (n+1) * (n+2)) / 3;
}

int main() {
    int n = 5;
    cout << "Sum = " << calcSeriesSum(n);
    return 0;
}

ผลลัพธ์

Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+10) is 70