到底是我的a,b和他的m,n不对应还是我没有进行非法判断呢?后来我想了下都不是,这题应该考的效率,于是:
import org.junit.Test;
import java.util.Date;
public class TestSum {
//普通for循环累和
public int sum1(int m, int n){
int sum=0;
for (int i = m; i <= n; i++) {
sum += i;
}
return sum;
}
//高斯算法累和
public int sum2(int m, int n){
return (m+n)*(n-m+1)/2;
}
//递归累和
public int sum3(int m, int n) {
if (m > n) return 0;
if (m == n) return m;
return m + n + sum3(m + 1, n - 1);
}
@Test
public void test1(){
//普通循环效率最低
Date start = new Date();
int sum = sum1(0, 100000000);
Date end = new Date();
System.out.println("普通for循环结果"+sum);
System.out.println("普通for循环耗时"+(end.getTime()-start.getTime()));
System.out.println("==================================");
//高斯运算最优
start = new Date();
sum = sum2(0, 100000000);
end = new Date();
System.out.println("高斯运算结果"+sum);
System.out.println("高斯运算耗时"+(end.getTime()-start.getTime()));
System.out.println("==================================");
//递归运算效率不错,但在数字过大时后会内存溢出
/*start = new Date();
sum = sum3(0, 90000);
end = new Date();
System.out.println("递归运算结果"+sum);
System.out.println("递归运算耗时"+(end.getTime()-start.getTime()));*/
}
}
算法理解: