首页 > 文章列表 > C程序中前n个自然数的平方和是多少?

C程序中前n个自然数的平方和是多少?

前n个 平方和 关键词提取:C程序
361 2023-08-30

前 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