hdu1001

来源:互联网 发布:英雄无敌7堡垒兵种数据 编辑:程序博客网 时间:2024/04/27 21:33

今天第一次去刷题,本科荒废的编程现在要从新拾起来,从刷题开始吧。大学本科没写过多少代码,现在读研了明显感觉压力很大,所以不得不开始练习了,学习永远不晚,知道自己的短处想办法弥补也算是幸运的事情,可惜现在的大学生都不明白自己缺啥。

废话不多少了,先讲讲做题的感受吧。其实大一是有机会参加ACM比赛的,但是错过了,这一错过了可改变了以后的路啊。现在算是主动示好ACM,也不知道怎么练习,就从简单的开始吧,如果大神读到这篇文章,可以为小弟提一点建议。

说题目吧,从hdu1001开始,一道简单的求和题目,但有一个小的陷阱,先亮题目吧。

Problem Description
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
100
Sample Output

5050
题目涉及的算法不难,大部分人都能想到公式:n*(n+1)/2,如果直接用这个公式计算结果,会得到wrong answer.为什么呢?注意题目有一句话,红色部分,计算结果必须是32位,所以直接用公式会出现益处的可能,所以在算法实现上有一个小改变,如下:
#include <stdio.h>int main(){    int n;    int result;    while (scanf("%d", &n)!=EOF){        if (n % 2 == 0)            result = n / 2 * (n + 1);        else            result = (n + 1) / 2 * n;        printf("%d\n", result);        printf("\n");    }}
这样就能Ac了。另外一种方法就是用一个循环求和,主要注意的地方就是不要超出32位。

0 0