前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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP