What happens under the hood, when you call IntProgression.sum()
?
Sample code:
val n: Int
val sum = (0..n).sum()
does Kotlin iterate all elements from 0 to n
?
// O(n)
var sum = 0
for (i in 0..n) {
sum += i
}
or does it use a formula for calculating the sum of arithmetic sequence? which I assume is more performant for large values of n
.
// O(1)
var sum = (0 + n) * (n + 1) / 2
No, Kotlin does not optimize the sum()
.
The function is an extension function on Iterable
(IntProgression
implements Iterable<Int>
). That function could implement different sum algorithms depending on the actual type, but it just loops over all elements of the Iterable:
var sum: Int = 0
for (element in this) {
sum += element
}
return sum