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

ผลรวมกำลังสองของ n จำนวนธรรมชาติแรก ในภาษา C

หาผลรวม 1² + 2² + 3² + ... + n²

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

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

วิธีที่ 2: ใช้สูตรคณิตศาสตร์ (เร็วกว่า O(1))

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

#include <stdio.h>
int main() {
    int n = 10;
    int sum = n * (n + 1) * (2 * n + 1) / 6;
    printf("Sum of squares of %d numbers = %d", n, sum);
    return 0;
}

ผลลัพธ์

Sum of squares of 10 natural numbers is 385