Skip to content

Instantly share code, notes, and snippets.

@karan-ta
Created March 23, 2023 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karan-ta/4c0071add3e5257bba99552a96ef3dcd to your computer and use it in GitHub Desktop.
Save karan-ta/4c0071add3e5257bba99552a96ef3dcd to your computer and use it in GitHub Desktop.
sieve of eratosthenes kotlin code
fun getPrime(n:Int){
val numArray = BooleanArray(n) {_ -> true}
var i = 2
while(i * i < n) {
//for each prime number less than square root of n :
if (numArray[i]) {
var j = i
while (j * i < n) {
//mark the multiples of that prime number as false . do this below n
numArray[j * i] = false
j++
}
i++
}
}
numArray.forEachIndexed { index, b ->
println(index)
println(b)
}
}
fun main() {
getPrime(16) // get prime numbers from 1 to 15 inclusive
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment