Sum Problem
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 167462 Accepted Submission(s): 39789
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.
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
我的最先想到的挫逼代码,真的是wa啊:
#include<stdio.h>
int main()
{
int i,j,n,a,sum=0;
while(scanf("%d%d",&a,&n)!=EOF)
{
//sum=n*(n+a)/2;
sum=(int)(n*(n+1.0)/2.0);
printf("1\n\n");
//printf("%d\n",sum);
printf("%d\n",sum);
}
return 0;
}
比较好的代码:
#include <stdio.h>
int main()
{
int n, sum;
while (scanf("%d", &n) !=EOF)
{
sum = 0;
while (n != 0)
{
sum += n--;
}
printf("%d\n\n", sum);
}
return 0;
}其实我在想它为什么没有超时。。。。。。
最不能让人忍受的是像下面这种代码也能AC
#include <stdio.h>
int sum(int);
int main(){
int input,output;
while (scanf("%d",&input)==1)
{
output = sum(input);
printf("%d\n\n",output);
}
return 0;
}
int sum(int n){
int sum,i;
sum=0;
for (i=1;i<=n;i++)
{
sum+=i;
}
return sum;
}
872

被折叠的 条评论
为什么被折叠?



