Created
March 15, 2021 08:39
-
-
Save yt8492/520f3843de7b20552e62dfecf222b290 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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