前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)21)/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