The demo here is an additive algorithm, such as 1,2,3,4.....N
That is: sum = 1+2+3+4......+n;
We can do this:
Copy Code code as follows:
/**
* Cyclic implementation of the cumulative 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;
}
Another method (Gauss method):
Copy Code code as follows:
/**
* Gauss method:<code> (n+1) *n/2</code><br>
* 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;
}
We can write a demo to test their differences:
Copy Code code as follows:
/**
*
*/
Package com.b510.arithmetic;
/**
* Cumulative algorithm to achieve <br>
*
* @date 2013-4-16
* @author Hongten
*
*/
public class Addarithmetic {
/**
* Cyclic implementation of the cumulative 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;
}
/**
* Gauss method:<code> (n+1) *n/2</code><br>
* 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) {
Cleans up memory, but does not necessarily perform
System.GC ();
You are 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 cyclic summation method to accumulate from [1] to [" +value+ "] When: [" + (End-start) + "]ms, Result:" + sum);
Cleans up memory, but does not necessarily perform
System.GC ();
Start = System.currenttimemillis ();
sum = Gaosi (value);
End = System.currenttimemillis ();
System.out.println ("Use Gauss method to add from [1] to [" +value+ "] When: [" + (End-start) + "]ms, Result:" + sum);
}
}
You can change the values of value in the Main method to test the system time they consume ....
Of course, different configurations of the machine running results are not the same ...
My machine operation condition:
Copy Code code as follows:
Use the cyclic accumulation method to accumulate from [1] to [10000000] When: [24]ms, Result: 50000005000000
Use the Gauss method to accumulate from [1] to [10000000] When: [0]ms, Result: 50000005000000