Jan Järfalk
03/14/2018, 7:31 PMfun 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…
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.