Home >Java >Javagetting Started >Three ways to calculate the sum of positive integers within 100 in Java
The method is as follows:
(Recommended tutorial: java course)
1. Brutal solution
Use for loop to directly solve the problem one by one, the algorithm complexity is O ( n ) O(n)O(n)
/** * <p>暴力解法</p> * @param startInclusive * @param endExclusive * @return */ public int sumByDirect(int startInclusive, int endExclusive){ int sum = 0; for (int i = startInclusive; i < endExclusive; i++) { sum += i; } return sum; }
2. Flow programming
is the same as the brute force solution, but uses declarations A flow programming style with less code and more readability
/** * <p>流式编程</p> * @param startInclusive * @param endExclusive * @return */ public int sumByStream(int startInclusive, int endExclusive){ return IntStream.range(startInclusive, endExclusive).sum(); }
3. Using the summation formula
Using the arithmetic sequence summation formula
complex The degree is O ( 1 ) O(1)O(1)
/** * <p>利用求和公式</p> * @param startInclusive * @param endExclusive * @return */ public int sumByFormula(int startInclusive, int endExclusive){ return ((startInclusive + endExclusive - 1) * (endExclusive - startInclusive) ) >> 1; }
Test:
@Test public void Test() { System.out.println("sumByDirect=" + sumByDirect(1, 101)); System.out.println("sumByStream=" + sumByStream(1, 101)); System.out.println("sumByFormula=" + sumByFormula(1, 101)); }
Output result:
sumByDirect=5050 sumByStream=5050 sumByFormula=5050
Related recommendations:javaGetting Started
The above is the detailed content of Three ways to calculate the sum of positive integers within 100 in Java. For more information, please follow other related articles on the PHP Chinese website!