等差數列各項平方交錯和
等差數列 (AP) 是一系列數字,其中兩個連續項之間的差相同。這個差值透過從第一個項中減去第二個項來計算。
讓我們來看一個等差數列的例子:
5, 7, 9, 11, 13, 15, ... 這個等差數列的公差(d)是2。這意味著每個後續元素都比前一個元素大2。該數列的首項(a)是5。
求第n項的通式為 an = a + (n-1)(d)
在這個問題中,我們給定一個等差數列,我們需要找到各項平方交錯和,數列的形式如下:
a12 - a22 + a32 - a42 + a52 +......
讓我們來看一個例子,以便更好地理解:
Input: n = 2 Output: -10
說明
12 - 22 + 32 - 42 = -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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP