您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

C程序中前n个偶数的平方和

2024/3/14 20:18:58发布31次查看
前n个偶数的平方和意味着,我们首先找到平方并将它们全部相加得到总和。
有两种方法可以找到前n个偶数的平方和
使用循环我们可以使用循环从1到n迭代,每次增加1,找到平方并将其加到总和变量中−
例子#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

以上就是c程序中前n个偶数的平方和的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product