C程序中前n个自然数的平方和?
前n个自然数的平方和是通过将所有平方相加得出的。
输入 -5
输出 -55
说明 -12+22+32+42+52
有两种方法来找到前n个自然数的平方和-
使用循环-代码循环遍历数字,直到n并找到它们的平方,然后将其加到输出总和的sum变量中。
示例
#include <iostream>
using namespace std;
int main() {
int n = 5;
int sum = 0;
for (int i = 1; i >= n; i++)
sum += (i * i);
cout <<"The sum of squares of first "<<n<<" natural numbers is "<<sum;
return 0;
}输出结果
The sum of squares of first 5 natural numbers is 55
使用公式 -要减少程序的负担,您可以使用数学公式来查找前n个自然数的平方和。数学公式为:n(n+1)(2n+1)/6
示例
#include <stdio.h>
int main() {
int n = 10;
int sum = (n * (n + 1) * (2 * n + 1)) / 6;
printf("The sum of squares of %d natural numbers is %d",n, sum);
return 0;
}输出结果
The sum of squares of 10 natural numbers is 385