Exercise: Prime numbers sequence
Implement a program that calculates and displays prime numbers. A prime number is a number that is divisible only by itself and 1. So, the first 5 numbers in this sequence should be 2, 3, 5, 7, 11...
This sequence should be infinite. The result should be of type BigInteger
. The first prime number is 2.
The easiest way to check if a number is prime is to check if it is divisible by any of the previous prime numbers. If it is not divisible by any of them, then it is prime. This is not the most efficient way to check if a number is prime, but it is good enough for this exercise.
val primes: Sequence<BigInteger> = sequence {
TODO()
}
This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in coroutines/sequences/Prime.kt. You can find there starting code and unit tests.
Once you are done with the exercise, you can check your solution here.
import org.junit.Test
import java.math.BigInteger
import kotlin.test.assertEquals
val primes: Sequence<BigInteger> = sequence {
TODO()
}
class PrimesTest {
@Test
fun `should calculate the first 10 prime numbers`() {
val primes = primes.take(10).toList()
val expected = listOf(
BigInteger("2"),
BigInteger("3"),
BigInteger("5"),
BigInteger("7"),
BigInteger("11"),
BigInteger("13"),
BigInteger("17"),
BigInteger("19"),
BigInteger("23"),
BigInteger("29"),
)
assertEquals(expected, primes)
}
@Test(timeout = 1000)
fun `should calculate 1000'th prime number`() {
val prime = primes.drop(1000).first()
assertEquals(BigInteger("7927"), prime)
}
}
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.