使用for
迴圈直接逐個求解,演演算法複雜度為
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;
}
同暴力解法一樣,不過使用了宣告式的流式程式設計,程式碼量更少並且更加的具有可讀性
/**
* <p>流式程式設計</p>
* @param startInclusive
* @param endExclusive
* @return
*/
public int sumByStream(int startInclusive, int endExclusive){
return IntStream.range(startInclusive, endExclusive).sum();
}
利用等差數列求和公式
S
n
=
(
a
1
+
a
2
)
×
n
2
S_n=\cfrac{(a_1+a_2)\times n}{2}
Sn=2(a1+a2)×n
複雜度為
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
public void Test() {
System.out.println("sumByDirect=" + sumByDirect(1, 101));
System.out.println("sumByStream=" + sumByStream(1, 101));
System.out.println("sumByFormula=" + sumByFormula(1, 101));
}
輸出:
sumByDirect=5050
sumByStream=5050
sumByFormula=5050