In this tutorial, you shall learn how to write a program to print prime numbers between given two numbers in Kotlin.
Kotlin – Print Prime Numbers
To print prime numbers between a given range in Kotlin, iterate between the given range of numbers, and for number in the range, check if it is a prime number. If it a prime number, print it, else continue with the next number in the range.
Program
In the following program, we read two numbers from user and print all the prime numbers between these two given numbers.
Main.kt
</>
Copy
fun isPrime(number: Int): Boolean {
if (number <= 1) {
return false
}
var i = 2
while ( i <= number/i ) {
if (number % i == 0) {
return false
}
i++
}
return true
}
fun main() {
print("Enter starting number : ")
val start = readLine()!!.toInt()
print("Enter ending number : ")
val end = readLine()!!.toInt()
println("Prime numbers in the range [$start, $end]")
for (i in start until end+1) {
if ( isPrime(i) ) {
println(i)
}
}
}
Output #1
Enter starting number : 10
Enter ending number : 50
Prime numbers in the range [10, 50]
11
13
17
19
23
29
31
37
41
43
47
Output #2
Enter starting number : 500
Enter ending number : 600
Prime numbers in the range [500, 600]
503
509
521
523
541
547
557
563
569
571
577
587
593
599
Related tutorials for the above program
Related Tutorials
Conclusion
In this Kotlin Tutorial, we learned how to print Prime numbers in the given range.