Created
January 21, 2018 16:04
-
-
Save cowlike/763cfa56939006f0e5113528083e8050 to your computer and use it in GitHub Desktop.
Kotlin prime number generation
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.buildIterator | |
import kotlin.coroutines.experimental.buildSequence | |
///not tail recursive! | |
fun primes(n: Int = 2): Sequence<Int> = buildSequence<Int> { | |
yield(n) | |
yieldAll(primes(n + 1).filter { x: Int -> x % n != 0 }) | |
} | |
///tail recursive version | |
val primesTR = { | |
var n = 2 | |
var acc: MutableList<Int> = mutableListOf() | |
generateSequence { | |
tailrec fun next(): Int { | |
if (acc.none { n % it == 0 }) { | |
acc.add(n) | |
return n | |
} | |
else { | |
n += 1 | |
return next() | |
} | |
} | |
next() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment