求前 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