首页 > 学院 > 开发设计 > 正文

HDU 1001 Sum Problem

2019-11-14 10:10:14
字体:
来源:转载
供稿:网友

Sum PRoblem

Time Limit: 1000/500 MS (java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 454929    Accepted Submission(s): 114527Problem DescriptionHey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n. InputThe input will consist of a series of integers n, one integer per line. OutputFor 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 新手的水题,本来没什么难度,但对于像我这样初上路的新手,还是会遇到很多问题,写下来促进自己提升。首先可以直接用叠加#include<stdio.h>int main() {int n , sum = 0;while (scanf("%d", &n) != EOF) {for (int i = 0; i <= n; i++) {sum += i;}printf("%d/n/n", sum);}return 0;}看起来没什么问题,但是提交上去却是Wrong Answer仔细看一下可以发现sum每完成一个SUM(n)后没有清零,把值带入了下一个SUM(n)的计算中,正确的代码应该为:#include<stdio.h>int main() {int n;while (scanf("%d", &n) != EOF) {int sum = 0; // sum应该在这里定义for (int i = 0; i <= n; i++) {sum += i;}printf("%d/n/n", sum);}return 0;}如果用公式做sum = (n+1)*n/2 则需要注意另一个问题。题目说结果不超过32bit,但是如果用公式做的话中间值(n+1)*n可能超过32bit,提交如下代码#include<stdio.h>int main() {int n, sum = 0;while (scanf("%d", &n) != EOF) {sum = (n+1)*n/2;printf("%d/n/n", sum);}return 0;}果然是Wrong Answer正确的代码
#include<stdio.h>int main() {    int n, sum = 0;    while (scanf("%d", &n) != EOF) {        if(n%2==0)           sum=n/2*(1+n);        else           sum=(n+1)/2*n;        printf("%d/n/n", sum);    }    return 0;}新手入门,处处是坑。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表