-
-
Save nakaly/642ed5eebd4b24ecb9e2b6856e255ea0 to your computer and use it in GitHub Desktop.
エラトステネスのふるい実装してみた
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
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