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

ผลรวมอนุกรม 1 + 2+2 + 3+3+3 + ... ใน C++

ภาพรวมปัญหา

หาผลรวมอนุกรม: 1 + 2+2 + 3+3+3 + ... + n (ซ้ำ n ครั้ง) = Σ i² จาก i=1 ถึง n

ตัวอย่าง

n = 4 → 1 + 2+2 + 3+3+3 + 4+4+4+4 = 1 + 4 + 9 + 16 = 30

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

1. Nested Loop (O(N²)) - ไม่แนะนำ

for (int i = 1; i <= n; i++)
    for (int j = 1; j <= i; j++)
        sum += i;

2. Single Loop (O(N)) - ใช้การคูณ

for (int i = 1; i <= n; i++)
    sum += i * i;

3. สูตรปิด (O(1)) - สูตรผลรวมกำลังสอง

Σ i² = n(n+1)(2n+1)/6

โค้ด C++ (สูตรปิด)

#include <iostream>
using namespace std;

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

int main() {
    int n = 7;
    cout << "The sum of series till " << n << " is " << calcSeriesSum(n);
    return 0;
}

ผลลัพธ์

N = 7 → 140