https://kotlinlang.org logo
j

Jan Järfalk

03/14/2018, 7:31 PM
Hi! I just wrote my first Kotlin app. 🎉 …and now I’m refactoring. I have this function that looks like this…
Copy code
fun getDivisors(n: Int): List<Int> {

    val divisors: MutableList<Int> = mutableListOf()
    val limit = Math.sqrt(n.toDouble()).toInt()

    for (i in 1..limit) {
        if (n % i == 0) {
            divisors.add(i)
            if (Math.pow(i.toDouble(), 2.0).toInt() != n) {
                divisors.add(n / i)
            }
        }
    }

    return divisors

}
…its not pretty, but it does the job. I am trying to do something like this…
Copy code
fun getDivisors(n: Int): List<Int> {

    val limit = Math.sqrt(n.toDouble()).toInt()

    return (1..limit).filter { n % it == 0 }.flatMap {
        val foo = Math.pow(it.toDouble(), 2.0).toInt() != n
        return when (foo) {
            true -> listOf(it, n/it)
            else -> listOf(it)
        }
    }

}
…but I can’t get it to work and it get no error… just nothing.