這裡的demo是一個累加演算法,如1,2,3,4.....n
即:sum = 1+2+3+4......+n;
我們可以這樣做:
for (long i = 1,v = value; i <= v; i++) {
sum += i;
}
return sum;
}
/**
* 累加演算法實作<br>
*
* @date 2013-4-16
* @author hongten
*
*/
public class AddArithmetic {
/**
* 循環實作累加方法
* @param value
* @return
*/
private static long cycle(long value) {
long sum = 0;
for (long i = 1,v = value; i <= v; i++) {
sum += i;
}
return sum;
}
/**
* 高斯方法:<code>(n+1)*n/2</code><br>
* you can read more from <a href="http://zhidao.baidu.com/question/411055258.html">Here</a>
* @param value
* @return
*/
private static long gaosi(long value) {
long sum = 0;
sum = (value + 1) * value / 2;
return sum;
}
public static void main(String[] args) {
//清理一下內存,但不一定會執行
System.gc();
// you should change value,then get the different results
long value = 10000000;
long sum = 0;
long start = System.currentTimeMillis();
sum = cycle(value);
long end = System.currentTimeMillis();
System.out.println("使用迴圈累加法從[1]累加到["+value+"]用時: ["+(end - start) + "]ms,結果:"+ sum);
//清理一下內存,但不一定會執行
System.gc();
start = System.currentTimeMillis();
sum = gaosi(value);
end = System.currentTimeMillis();
System.out.println("使用高斯方法從[1]累加到["+value+"]用時: ["+(end - start) + "]ms,結果:"+ sum);
}
}
當然不同配置的機器運作結果是不一樣的...
我機器運作狀況: