Author 林方圆
Organization 广东东软学院
计算s=1+(1+2)+(1+2+3)+……+(1+2+……+n)。
输入在一行中给出n的值。
在输出行显示计算出的结果。
在这里给出一组输入。例如:
20
在这里给出相应的输出。例如:
sum=1540
By SinhoMoeme
題解作者 史行·某萌
There is a sequence which the value of each item is adding from 1 to current number of items.
The length of the sequence is
有一個序列,其每個項目的值是從 1 加到當前項目的數量。
序列的長度是
#include<stdio.h> int n,s=0; int main(){ scanf("%d",&n); for(int i=1;i<=n;++i){ for(int j=1;j<=i;++j) s+=j; } printf("sum=%d",s); return 0; }
#include<stdio.h> int n,now=0,s=0; int main(){ scanf("%d",&n); for(int i=1;i<=n;++i){ now+=i; s+=now; } printf("sum=%d",s); return 0; }
First let me explain the BF solution. Input for enumerate for enumerate for will add
首先我來解釋這個暴力解法。輸入 for 迴圈從 for 迴圈會從 for 迴圈會將
for(int i=1;i<=n;++i){ for(int j=1;j<=i;++j) s+=j; }
We can optimize this code since for each item, if it have a predecessor, the value of it equals the value of its predecessor plus
我們可以優化這段程式碼,因為對於每個項目,如果它有前任者,它的值等於前任者的值加上
for(int i=1;i<=n;++i){ now+=i; s+=now; }