初接触ACM,问个问题?

qepjatdwj 2009-06-30 11:32:22
杭电1001题:
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

我的这个为什么是wrong answer啊?

#include<stdio.h>
int main(void)
{
int sum,n;
while((scanf("%d",&n))!=EOF)
{
sum=n*(n+1)/2;
printf("%d\n\n",sum);
}
return 0;
}

用下面这个却可以通过:

#include<stdio.h>
main()
{
int n,i,sum=0;

while((scanf("%d",&n))!=EOF)
{
i=1;
sum=0;
while(i<=n)
{
sum=sum+i;
i=i+1;
}

printf("%d\n\n",sum);
}
}

...全文
54 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
liao05050075 2009-06-30
  • 打赏
  • 举报
回复
the result will be in the range of 32-bit signed integer

可能它有比较大的数据,于是你n*(n+1)已经超过了 32-bit signed integer的范围了,变成了负数。

你可以试一试,把 int 换成Long long

#include<stdio.h>
int main(void)
{
long long sum,n;
while((scanf("%lld",&n))!=EOF)
{
sum=n*(n+1)/2;
printf("%lld\n\n",sum);
}
return 0;
}


sunzerui 2009-06-30
  • 打赏
  • 举报
回复
学习!
liao05050075 2009-06-30
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 qepjatdwj 的回复:]
楼上能解释一下为什么吗?是对的。
[/Quote]

while((scanf("%d",&n))!=EOF)
{
if((n&1) == 0)
sum=n/2*(n+1);
else
sum=(n+1)/2*n;
printf("%d\n\n",sum);
}

事实上,我已经解释了。
n*(n+1)有可能超过了 32-bit signed integer的范围,
于是先除于2,就可以避免这个问题
qepjatdwj 2009-06-30
  • 打赏
  • 举报
回复
楼上能解释一下为什么吗?是对的。
fire_woods 2009-06-30
  • 打赏
  • 举报
回复
我猜这样就可以了.

#include<stdio.h>
int main(void)
{
int sum,n;
while((scanf("%d",&n))!=EOF)
{
if((n&1) == 0)
sum=n/2*(n+1);
else
sum=(n+1)/2*n;
printf("%d\n\n",sum);
}
return 0;
}

33,028

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧