Skip to content

Instantly share code, notes, and snippets.

@nakaly
Created February 6, 2021 18:30
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 nakaly/642ed5eebd4b24ecb9e2b6856e255ea0 to your computer and use it in GitHub Desktop.
Save nakaly/642ed5eebd4b24ecb9e2b6856e255ea0 to your computer and use it in GitHub Desktop.
エラトステネスのふるい実装してみた
fun main() {
for (i in 3 until Int.MAX_VALUE step 1000) {
val time = measureTimeMillis { eratosthenes(i) }
println("$i : $time")
}
// eratosthenes(1000).forEachIndexed{i, isPrime -> println("$i : $isPrime")}
}
fun eratosthenes(n: Int) : Array<Boolean> {
var numbers = arrayOf<Boolean>()
for (i in 0 until n) {
numbers += i % 2 != 0
}
numbers[1] = false
numbers[2] = true
for (i in 3..n+1 step 2) {
if (i * i > n) {
break
}
if (!numbers[i]) {
continue
}
for (j in i*2 until n step i) {
numbers[j] = false
}
}
return numbers
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment