C 程式求前 n 個偶數的平方和
前 n 個偶數的平方和意味著我們首先求平方,然後把所有平方數加起來得到總和。
有兩種方法可以求出前 n 個偶數的平方和
使用迴圈
我們可以使用迴圈,從 1 到 n 遞增 1,每次求出平方並將其新增到 sum 變數中 −
示例
#include <iostream>
using namespace std;
int main() {
int sum = 0, n =12;
for (int i = 1; i <= n; i++)
sum += (2 * i) * (2 * i);
cout <<"Sum of first "<<n<<" natural numbers is "<<sum;
return 0;
}輸出
Sum of first 12 natural numbers is 2600
此程式的複雜度以 0(n) 順序增加。因此,對於較大的 n 值,程式碼需要時間。
使用數學公式
為了解決這個問題,匯出了一個數學公式,即偶數之和為 2n(n+1)(2n+1)/3
示例
#include <iostream>
using namespace std;
int main() {
int n = 12;
int sum = (2*n*(n+1)*(2*n+1))/3;
cout <<"Sum of first "<<n<<" natural numbers is "<<sum;
return 0;
}輸出
Sum of first 12 natural numbers is 2600
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP