前n个自然数的平方和之和
前n个自然数的平方和之和是指求从1到n的平方和的总和。这个序列求出从1到n每个数的平方和,并将这些和加到一个sum变量中。
前4个自然数的平方和之和是:
sum = (12) + (12 + 22 ) + (12 + 22 + 32) + (12 + 22 + 32 + 42 ) = 1 + 5 + 14 + 30 = 50
有两种方法可以求前n个自然数的平方和之和。
1) 使用for循环。
在这种方法中,我们将循环遍历从1到N的每个数字,找到平方和,然后将这个平方和添加到sum变量中。此方法需要对n个数字进行迭代,因此对于较大的数字,它将非常耗时。
示例
#include <stdio.h> int main() { int n = 6; int sum = 0; for (int i = 1; i <= n; i++) sum += ((i * (i + 1) * (2 * i + 1)) / 6); printf("The square-sum of first %d natural number is %d",n,sum); return 0; }
输出
The square-sum of first 6 natural number is 196
2) 使用数学公式:
根据求第n项和该序列的通项公式,可以推导出一个数学公式来求前n个自然数的平方和之和。求前n个自然数的平方和之和的公式是 sum = n*(n+1)*(n+1)*(n+2)/12
基于此公式,我们可以编写一个程序来求和:
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include <stdio.h> int main() { int n = 6; int sum = (n*(n+1)*(n+1)*(n+2))/12; printf("The square-sum of first %d natural number is %d",n,sum); return 0; }
输出
The square-sum of first 6 natural number is 196
广告