求前 n 个自然数的平方和C程序?
前 n 个自然数平方的和通过将所有平方相加得到。
输入- 5
输出- 55
说明- 12 + 22 + 32 + 42 + 52
求前n个自然数平方和有两种方法:
使用循环- 代码循环遍历数字,直至n,并找出它们的平方,然后将此值添加到输出和的总和变量中。
示例
#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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP