前n個奇數平方和的和


前n個奇數的平方和系列在該系列中用了前n個奇數的平方。

該系列為:1、9、25、49、81、121...

該系列也可以寫成 - 12、32、52、72、92、112...

該系列的和有以下的數學公式 -

n(2n+1)(2n-1)/3= n(4n2 - 1)/3

我們舉個例子:

Input: N = 4
Output: sum =

解釋

12 + 32 + 52 + 72 = 1 +9+ 25 + 49 = 84

使用公式,和 = 4(4(4)2- 1)/3 = 4(64-1)/3 = 4(63)/3 = 4*21 = 84 這些方法都很不錯,但是使用數學公式的方法更好,因為它不用觀察值,從而可以減少時間複雜度。

示例

#include <stdio.h>
int main() {
   int n = 8;
   int sum = 0;
   for (int i = 1; i <= n; i++)
      sum += (2*i - 1) * (2*i - 1);
   printf("The sum of square of first %d odd numbers is %d",n, sum);
   return 0;
}

輸出

The sum of square of first 8 odd numbers is 680

示例

#include <stdio.h>
int main() {
   int n = 18;
   int sum = ((n*((4*n*n)-1))/3);
   printf("The sum of square of first %d odd numbers is %d",n, sum);
   return 0;
}

輸出

The sum of square of first 18 odd numbers is 7770

更新於:2019 年 8 月 19 日

3K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.