n = 4
Now we will find the sum of numbers for every number from 1 to 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 - 使用数学公式(高效)
在这种方法中,我们将使用两个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
我们有一个数学公式用于求解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
以上就是C程序中的前n个自然数之和的详细内容,更多请关注php中文网其它相关文章!
已抢23166个
抢已抢117571个
抢已抢139135个
抢已抢6189个
抢已抢35201个
抢已抢7835个
抢