Kotlin 找素数/质数

质数又称素数

质数是指在大于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
}

输出

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/124130056
今日推荐