1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-09-19 14:16:55 +02:00
CodeWars/7kyu/sum_of_odd_numbers/solution.kt

13 lines
405 B
Kotlin
Raw Normal View History

// How to get k-th odd number: p = 2k + 1 (zero indexed)
// Decomposition:
// 1. Find out how many odd numbers we have in front
// 2. Figure out next index
// 3. Sum those numbers
private fun kthOdd(k: Int): Int = 2*k + 1
private fun oddNumbersBefore(n: Int) = n.times(n + 1).div(2)
fun rowSumOddNumbers(n: Int): Int =
(oddNumbersBefore(n - 1)..oddNumbersBefore(n) - 1)
.sumOf { kthOdd(it) }