mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-09 11:09:07 +01:00
12 lines
405 B
Kotlin
12 lines
405 B
Kotlin
// 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) }
|