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

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

อนุกรม 2, 10, 30, 68, ... สามารถแยกได้เป็นผลรวมของสองอนุกรม: จำนวนธรรมชาติ (1, 2, 3, 4...) และกำลังสามของจำนวนธรรมชาติ (1³, 2³, 3³, 4³...)

2 = 1 + 1³, 10 = 2 + 2³, 30 = 3 + 3³, 68 = 4 + 4³

สูตรผลรวม

Sum = n(n+1)/2 + [n(n+1)/2]²

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

#include <stdio.h>

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

ผลลัพธ์

the sum of series till 6 is 462