Last active
February 16, 2018 23:56
-
-
Save ersin-ertan/3d18d2a02df03e6074c700f10dcd8c1e to your computer and use it in GitHub Desktop.
using Sequence<Int>
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
import kotlin.coroutines.experimental.buildSequence | |
import kotlin.system.measureTimeMillis | |
fun sieve(isPrime: Int, ints: Sequence<Int>): Boolean = with(ints.first()) { | |
return when { | |
isPrime < 2 -> false | |
isPrime == 2 -> true | |
isPrime == this -> true | |
isPrime.rem(2) == 0 -> false | |
// isPrime.and(1) == 0 -> false // same way to check if number is even | |
this > isPrime -> false | |
else -> sieve(isPrime, ints.filter { n -> n.rem(this) != 0 }) | |
} | |
} | |
fun main(args: Array<String>) { | |
val lazySeq = buildSequence { for (i in 3..Int.MAX_VALUE step 2) yield(i) } | |
println("Duration = ${measureTimeMillis { println("isPrime(4057) = ${sieve(4057, lazySeq)}") }}ms") | |
// (2..200).forEach { println("isPrime($it) = ${sieve(it, lazySeq)}") } | |
} | |
// isPrime(4057) = true | |
// Duration = 839ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment