1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-25 10:11:56 +01: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) }