在Kotlin中获取数字的因子
Kotlin全新,我怎么找到一个数字的因素?
例如24应该给1,2,3,4,6,8,12,24?
我知道如何做这个Python列表的理解,但不知道如何在Kotlin正确做到这一点。
不知道如何在Kotlin中做“列表理解”,而是可以使用如下的factorsOfNumbers
函数:
fun factorsOfNumber(num: Int) : MutableList<Int> { val factors = mutableListOf<Int>() if (num < 1) return factors (1..num / 2) .filter { num % it == 0 } .forEach { factors.add(it) } factors.add(num) return factors } fun main(args: Array<String>) { val number = 24 println("The factors of $number are: " + factorsOfNumber(number).joinToString()) }
输出:
The factors of 24 are: 1, 2, 3, 4, 6, 8, 12, 24
相关的文档,以了解它是如何工作的如下:
- 集合:List,Set,Map ( MutableList stuff)
- 范围 (
(1..num / 2)
部分) - 科特林成语 (EveryThing else)