1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 11:09:07 +01:00
CodeWars/7kyu/sum_of_odd_numbers/solution.kt
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

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) }