Skip to content

Instantly share code, notes, and snippets.

@Sch3lp
Last active December 18, 2019 14:27
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 Sch3lp/9d4df76b6abf97351c3be6e79432a2f6 to your computer and use it in GitHub Desktop.
Save Sch3lp/9d4df76b6abf97351c3be6e79432a2f6 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
val primes: Sequence<Int> = sequence {
var numbers = generateSequence(2) { it + 1 }
while (true) {
val prime = numbers.first()
yield(prime)
numbers = numbers
.drop(1)
.filter { it % prime != 0 }
}
} // works
primes.take(10).toList()
// 2, 3, 5, 7, 11, 13, 17, 19, 23, 29
val primes2: Sequence<Int> = sequence {
var numbers = generateSequence(2) { it + 1 }
var prime: Int
while (true) {
prime = numbers.first()
yield(prime)
numbers = numbers
.drop(1)
.filter { it % prime != 0 }
}
} // does not work
primes2.take(10).toList()
// 2, 3, 5, 6, 7, 8, 9, 10, 11, 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment