Home>Article>Java> Three ways to calculate the sum of positive integers within 100 in Java

Three ways to calculate the sum of positive integers within 100 in Java

王林
王林 forward
2020-10-22 18:15:15 3468browse

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)

/** * 

暴力解法

* @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

/** * 

流式编程

* @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)

/** * 

利用求和公式

* @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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete