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

更新於:2019 年 8 月 8 日

1 千次+瀏覽

開啟您的 職業 之旅

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.