HDU 1001 Sum Problem

来源:互联网 发布:软件功能需求说明书 编辑:程序博客网 时间:2024/05/16 10:25

这是一道带着坑的水题。

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
1100
 

Sample Output
15050
 

以上为题意,坑就在下划线处,一开始我天真的直接用公式计算了和,即(1+n)*n/2,结果很不幸的出现了WA,很纳闷,以为是格式问题,但发现我的格式没有错误,看了讨论区,有的说用double,有的说用long long,我以为是超出范围了,但叠加计算提交是正确的。其实用公式计算确实可能会超出int范围,先计算的是(1+n)*n,在这里会产生溢出,所以我们可以考虑改变计算顺序,即改为(1+n)/2*n,这样它就不会溢出,但新问题出现了,除以2的操作只能是偶数操作,所以进行判断之后就可以了。贴上源代码。

/*************************************************************************    > File Name: 1001_Sum_Problem.c    > Author:lucifer lawliet    > Mail:hnzhrh@foxmail.com    > Created Time: 2016年06月06日 星期一 15时07分22秒 ************************************************************************/#include<stdio.h>int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        if(n&1)            printf("%d\n\n",(1+n)/2*n);        else            printf("%d\n\n",n/2*(n+1));    }}

0 0
原创粉丝点击