C程序中前n个自然数的总和
找到求和的总和的概念被找到,使得首先,我们将找到直到n的数的总和,然后将所有和相加以获得一个值,该值将是和的总和,这就是我们想要的总和。
对于这个问题,给我们一个数字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个自然数之和,我们有两种方法:
方法1-使用for循环(效率低下)
方法2-使用数学公式(有效)
方法1-使用for循环
在此方法中,我们将使用两个for循环来查找总和。内循环找到自然数之和,外循环将该总和加到sum2并将该数字加一。
示例
#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
方法2-使用数学公式
我们有一个数学公式来查找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