1001 Sum Problem
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 24175 Accepted Submission(s): 5066
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
1
100
Sample Output
1
5050
//*************************程序代码******************************************************
import java.io.*;
public class hd1001 {
/**
* @param args
*/
public static int sumn(int n){
/*if(n%2==0)
return (n/2)*(1+n);
else
return ((1+n)/2)*n;*/
int sum=0;
for(int i=1;i<=n;i++){
sum=sum+i;
}
return sum;
}
public static void main(String[] args) {
// TODO 自动生成方法存根
try {
File file1=new File("F:\\eclipse\\hdacm\\1001\\1001.txt");
File file2=new File("F:\\eclipse\\hdacm\\1001\\1001a.txt");
BufferedReader input=new BufferedReader(new FileReader(file1));
BufferedWriter output=new BufferedWriter(new FileWriter(file2));
String tempString=null;
while ((tempString = input.readLine()) != null) {
int n=Integer.parseInt(tempString);
output.newLine();
}
output.close();
input.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
//*************************程序代码******************************************************
注:本题看似简单,其实里面有陷阱,在使用(N+1)*N/2公式时,(N+1)*N有可能已经越界,所以要先除2,或是用最原始的循环办法
posted on 2008-06-01 04:12
poower 阅读(277)
评论(0) 编辑 收藏