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

ผลรวมของ Square-Sums ของ n จำนวนธรรมชาติแรก


Sum of square-sums ของ n จำนวนธรรมชาติแรก คือ หาผลรวมของ "ผลรวมกำลังสอง" ยาว n จำนวน นั่นคือ หาผลรวมกำลังสองของแต่ละจำนวนถึง n แล้วบวกผลรวมเหล่านั้นเข้าด้วยกัน

Sum of square-sum ของ 4 จำนวนแรก:

sum = (1^2) + (1^2 + 2^2) + (1^2 + 2^2 + 3^2) + (1^2 + 2^2 + 3^2 + 4^2) = 1 + 5 + 14 + 30 = 50

มี 2 วิธี:

1) ใช้ For Loop วน 1 ถึง N หา Square-sum แต่ละรอบ บวกสะสม วิธีนี้ใช้เวลา O(n)

ตัวอย่าง

#include <stdio.h>
int main() {
    int n = 6;
    int sum = 0;
    for (int i = 1; i <= n; i++)
        sum += ((i * (i + 1) * (2 * i + 1)) / 6);
    printf("The square-sum of first %d natural number is %d", n, sum);
    return 0;
}

ผลลัพธ์

The square-sum of first 6 natural number is 196

2) ใช้สูตรคณิตศาสตร์ สูตร: sum = n*(n+1)*(n+1)*(n+2)/12

ตัวอย่าง

#include <stdio.h>
int main() {
    int n = 6;
    int sum = (n * (n+1) * (n+1) * (n+2)) / 12;
    printf("The square-sum of first %d natural number is %d", n, sum);
    return 0;
}

ผลลัพธ์

The square-sum of first 6 natural number is 196