Sum Problem
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 454929 Accepted Submission(s): 114527
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
新手的水题,本来没什么难度,但对于像我这样初上路的新手,还是会遇到很多问题,写下来促进自己提升。
首先可以直接用叠加
#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;
}
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;
}
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) {
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; }
新手入门,处处是坑。