Sum Problem
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 356729 Accepted Submission(s): 89599
Problem Description
Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).
In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + … + n.
Input
The input will consist of a series of integers n, one integer per line.
Output
For each case, output SUM(n) in one line, followed by a blank line. You may assume the result will be in the range of 32-bit signed integer.
Sample Input
1
100
Sample Output
1
5050
说明:
这个问题看似非常非常简单,在头脑中立刻会想到一些方法来解决。
例如,我下面贴一些代码咱看一下:
代码1:
#include<stdio.h>
int sum(int n);
int sum(int n)
{
int i=1,sum=0;
while(i<=n)
{
sum+=i;
i++;
}
return sum;
return 0;
}
int main()
{
int a;
while(scanf("%d/n",&a)!=EOF)
printf("%d\n",sum(a));
return 0;
}
这个代码在编译器上运行绝对没问题,采用函数化的方法,能够得出正确结果,于是提交,错了。这我就奇怪了,为什么呢?我想是不是时间复杂度过大,这个复杂度是O(n)。于是又想到了高斯老前辈的公式方法,于是乎又写了下面的代码,时间复杂度为O(1):
代码2:
#include<stdio.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
printf("%d\n",(n+1)*n/2);
return 0;
}
于是信誓旦旦的提交了,结果错误!什么情况?
后来注意到题中有一句话:You may assume the result will be in the range of 32-bit signed integer.要求求和结果是32位有符号整数。所以咯,我得调整一下策略,将公式的前半部分先进行除2,在进行乘法运算。分奇偶讨论如下:
- 偶数时:n/2*(n+1)
- 奇数时:(n+1)/2*n
于是有下面的代码3:
#include<stdio.h>
int main()
{
int n,sum;
while(scanf("%d",&n)!=EOF)
{
if(n%2==0)
{
sum=n/2*(n+1);
}
else
{
sum=(n+1)/2*n;
}
printf("%d\n",sum);
}
return 0
}
于是乎又信誓旦旦的提交,结果还不能通过!!!神马情况?
还得看题,又看了一遍题,发现丢掉了重点信息:followed by a blank line!!!好吧于是输出时又加了一个 \n,才得以AC。
代码如下4:
#include<stdio.h>
int main()
{
int n,sum;
while(scanf("%d",&n)!=EOF)
{
if(n%2==0)
{
sum=n/2*(n+1);
}
else
{
sum=(n+1)/2*n;
}
printf("%d\n\n",sum);
}
return 0;
}
当然,如下代码5也可以:
#include<stdio.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
if(n%2==0)
{
printf("%d\n\n",n/2*(n+1));
}
else
{
printf("%d\n\n",(n+1)/2*n);
}
}
return 0;
}
通过这个一个小题,我首先懂得了理解正确理解题意很重要,其次要注意问题的时间复杂度,尽量简化,以最简单的计算方法去处理。