How to find the sum of all the primes below 10000 (ten thousand) in Kotlin

1 Answer

0 votes
import kotlin.math.sqrt
import kotlin.math.floor

fun isPrime(n: Int): Boolean {
    if (n < 2 || (n % 2 == 0 && n != 2)) return false

    val limit = floor(sqrt(n.toDouble())).toInt()
    for (i in 3..limit step 2) {
        if (n % i == 0) return false
    }

    return true
}

fun main() {
    val num = 10000
    var sum = 0

    for (i in 2 until num) {
        if (isPrime(i)) {
            sum += i
        }
    }

    println("sum = $sum")
}


 
  
/*
run:
 
sum = 5736396

*/

 



answered Jul 26, 2025 by avibootz
...