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