Skip to content

Instantly share code, notes, and snippets.

@cowlike
Created January 21, 2018 16:04
Show Gist options
  • Save cowlike/763cfa56939006f0e5113528083e8050 to your computer and use it in GitHub Desktop.
Save cowlike/763cfa56939006f0e5113528083e8050 to your computer and use it in GitHub Desktop.
Kotlin prime number generation
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