Cấp số cộng (AP) là dãy số hiệu giữa hai số liên tiếp không đổi. Ví dụ: 5, 7, 9, 11, 13, 15... công sai d=2, số hạng đầu a=5. Công thức số hạng thứ n: aₙ = a + (n-1)d.
Bài toán: cho AP, tìm tổng chuỗi bình phương đổi dấu: a₁² - a₂² + a₃² - a₄² + a₅² + ...
Ví dụ:
Input: n = 2 Output: -10
Giải thích
1² - 2² + 3² - 4² = -10
Ví dụ
#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;
}
Kết quả
The sum of series is -36