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

ผลรวมกำลังสองของ n จำนวนคู่แรก ในภาษา C

หาผลรวม (2)² + (4)² + (6)² + ... + (2n)²

วิธีที่ 1: ใช้ลูป

#include <iostream>
using namespace std;
int main() {
    int n = 12, sum = 0;
    for (int i = 1; i <= n; i++) sum += (2*i)*(2*i);
    cout << "Sum = " << sum;
    return 0;
}

วิธีที่ 2: ใช้สูตรคณิตศาสตร์

Sum = 2n(n+1)(2n+1) / 3

#include <iostream>
using namespace std;
int main() {
    int n = 12;
    int sum = 2 * n * (n + 1) * (2 * n + 1) / 3;
    cout << "Sum = " << sum;
    return 0;
}

ผลลัพธ์

Sum of first 12 even squares = 2600