C语言程序中前n个自然数之和
求整数之和的概念是这样的:首先,我们求出从1到n的数的和,然后将所有这些和加起来,得到一个值,这个值就是我们想要的和的和。
在这个问题中,我们给定一个数字n,我们需要求出从1到n的和的和。让我们举个例子来求这个和。
n = 4
现在我们求从1到4每个数字的数的和
Sum of numbers till 1 = 1 Sum of numbers till 2 = 1 + 2 = 3 Sum of numbers till 3 = 1 + 2 + 3 = 6 Sum of numbers till 4 = 1 + 2 + 3 + 4 = 10 Now we will find the sum of sum of numbers til n : Sum = 1+3+6+10 = 20
求前n个自然数的和的和,我们有两种方法
方法一 − 使用for循环(效率低)
方法二 − 使用数学公式(效率高)
方法一 − 使用for循环
在这个方法中,我们将使用两个for循环来求和的和。内循环求自然数之和,外循环将这个和加到sum2中,并将数字加1。
示例
#include <stdio.h>
int main() {
int n = 4;
int sum=0, s=0;
for(int i = 1; i< n; i++){
for(int j= 1; j<i;j++ ){
s+= j;
}
sum += s;
}
printf("the sum of sum of natural number till %d is %d", n,sum);
return 0;
}输出
The sum of sum of natural number till 4 is 5
方法二 − 使用数学公式
我们有一个数学公式可以求前n个自然数的和的和。数学公式法是一种高效的方法。
求前n个自然数的和的和的数学公式
sum = n*(n+1)*(n+2)/2
示例
#include <stdio.h>
int main() {
int n = 4;
int sum = (n*(n+1)*(n+2))/2;
printf("the sum of sum of natural number till %d is %d", n,sum);
return 0;
}输出
the sum of sum of natural number till 4 is 60
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP