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

ผลรวมอนุกรมกำลังสอง AP ที่มีเครื่องหมายสลับกัน


Arithmetic Progression (AP) คืออนุกรมที่ความต่างระหว่างตัวติดกันคงที่ ความต่าง = ตัวที่ 2 - ตัวที่ 1

ตัวอย่าง AP: 5, 7, 9, 11, 13, 15... ความต่าง d=2 ตัวแรก a=5

สูตรทั่วไปหาตัวที่ n: a_n = a + (n-1)d

โจทย์: หาผลรวมอนุกรมกำลังสองเครื่องหมายสลับ: a1^2 - a2^2 + a3^2 - a4^2 + ...

ตัวอย่าง:

Input: n = 2 Output: -10

คำอธิบาย

1^2 - 2^2 + 3^2 - 4^2 = -10

ตัวอย่าง

#include <stdio.h>
int main() {
    int n = 4;
    int a[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    int res = 0;
    for (int i = 0; i < 2 * n; i++) {
        if (i % 2 == 0) res += a[i] * a[i];
        else res -= a[i] * a[i];
    }
    printf("The sum of series is %d", res);
    return 0;
}

ผลลัพธ์

The sum of series is -36