质数又称素数

质数是指在大于1的​​自然数​​​中,除了1和它本身以外不再有其他​​因数​​的自然数。

fun main() {
//找素数 通常写法
val numbers = listOf<Int>(213, 4, 534, 646, 757, 8, 97, 9);
val primes = numbers.filter { it.isPrime() }
println(primes)
//高阶函数引用
val primes2 = numbers.filter { number ->
(2 until number).map { number % it }.none { it == 0 }
}
println(primes2)


}

private fun Int.isPrime(): Boolean {
if (this == 1) return false
if (this == 2) return true
if (this % 2 == 0) return false
for (i in 3..Math.sqrt(this.toDouble()).toInt() step 2) {
if (this % i == 0) return false
}
return true
}

输出

Kotlin 找素数/质数_Math