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

ผลรวม n จำนวนแรกของอนุกรม 2, 6, 12, 20, 30, ... ในภาษา C

อนุกรม 2, 6, 12, 20, 30, ... สามารถแยกได้เป็น (1+1²), (2+2²), (3+3²), (4+4²), ...

สูตรผลรวม

  • Sum₁ = 1+2+3+... = n(n+1)/2
  • Sum₂ = 1²+2²+3²+... = n(n+1)(2n+1)/6
  • Total = n(n+1)/2 + n(n+1)(2n+1)/6

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

#include <stdio.h>

int main() {
    int n = 3;
    int sum = ((n * (n + 1)) / 2) + ((n * (n + 1) * (2 * n + 1)) / 6);
    printf("the sum series till %d is %d", n, sum);
    return 0;
}

ผลลัพธ์

The sum of series till 3 is 20