Sum Problem
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 534617 Accepted Submission(s): 135951
Total Submission(s): 534617 Accepted Submission(s): 135951
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
1100
Sample Output
15050
Author
DOOM III
题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1001
用等差数列求解的时候,不要用int,因为n(n-1)的数据范围超出了int的数据范围。
import java.util.*;
public class Main extends Object {
private static final Scanner cache = new Scanner(System.in);
public static void main(String[] args) {
while (cache.hasNext()) {
long number = cache.nextLong();
long SUM = 0;//注意,求和时,不要用int,因为在执行的过程中,计算的值会超过int
SUM = number + number * (number - 1) / 2;
System.out.println(SUM);
System.out.println();
}
}
}