Skip to content

Instantly share code, notes, and snippets.

@yt8492
Created March 15, 2021 08:39
Show Gist options
  • Save yt8492/520f3843de7b20552e62dfecf222b290 to your computer and use it in GitHub Desktop.
Save yt8492/520f3843de7b20552e62dfecf222b290 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
class Sieve(val max: Int) {
private val isPrimeArray: BooleanArray
init {
val array = BooleanArray(max + 1) {
true
}
array[0] = false
array[1] = false
val root = sqrt(max.toDouble()).toInt()
for (i in 0..root) {
if (array[i]) {
for (j in i * i until array.size step i) {
array[j] = false
}
}
}
isPrimeArray = array
}
fun isPrime(x: Int): Boolean {
if (x > max) {
throw IllegalArgumentException("x should same or smaller than $max")
}
return isPrimeArray[x]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment