C ++中前n个自然数之和
在此问题中,要找到前n个自然数之和,我们将找到从1到n的所有数字之和,并将它们加在一起以求和。
让我们举个例子来学习这个概念,
Input : 4 Output : 10 Explanation : Sum of first 1 natural number = 1 Sum of first 2 natural number = 1 + 2 = 3 Sum of first 3 natural number = 1 + 2 +3 = 6 Sum of first 4 natural number = 1 + 2 + 3 + 4 = 10 Sum of sum of 4 natural number = 1 + 3 + 6 + 10 = 20
示例
#include <iostream> using namespace std; int sumofSum(int n){ int sum = 0; for (int i=1; i<=n; i++) sum += i*(i+1)/2; return sum; } int main(){ int n = 4; cout<<"先加总和 "<<n<<"natural numbers is "<<sumofSum(n); return 0; }
输出结果
先加总和 4natural numbers is 20