Home > Java > Javagetting Started > body text

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

王林
Release: 2020-10-22 18:16:09
forward
3581 people have browsed it

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;
    }
Copy after login

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();
    }
Copy after login

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;
    }
Copy after login

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));
    }
Copy after login

Output result:

sumByDirect=5050
sumByStream=5050
sumByFormula=5050
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template