The demo here is an accumulation algorithm, such as 1,2,3,4...n
That is: sum = 1+2+3+4...+n;
We can do this:
for (long i = 1,v = value; i <= v; i++) {
sum += i;
}
return sum;
}
/**
* Implementation of accumulation algorithm<br>
*
* @date 2013-4-16
* @author hongten
*
*/
public class AddArithmetic {
/**
* Loop to implement accumulation method
* @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;
}
/**
* Gaussian method:<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) {
//Clean up the memory, but it may not be executed.
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("Use the loop accumulation method to accumulate from [1] to ["+value+"], time taken: ["+(end - start) + "]ms, result: "+ sum);
//Clean up the memory, but it may not be executed.
System.gc();
start = System.currentTimeMillis();
sum = gaosi(value);
end = System.currentTimeMillis();
System.out.println("Use Gaussian method to accumulate from [1] to ["+value+"], time taken: ["+(end - start) + "]ms, result: "+ sum);
}
}
Of course, the running results of machines with different configurations are different...
The operation status of my machine: