Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Kotlin Program to Display Prime Numbers Between Intervals Using Function
In this program, you'll learn to display all prime numbers between the given intervals using a function in Kotlin.
To find all prime numbers between two integers, checkPrimeNumber() function is created. This function checks whether a number is prime or not.
Example: Prime Numbers Between Two Integers
fun main(args: Array<String>) {
var low = 20
val high = 50
while (low < high) {
if (checkPrimeNumber(low))
print(low.toString() + " ")
++low
}
}
fun checkPrimeNumber(num: Int): Boolean {
var flag = true
for (i in 2..num / 2) {
if (num % i == 0) {
flag = false
break
}
}
return flag
}
When you run the program, the output will be:
23 29 31 37 41 43 47
In the above program, we've created a function named checkPrimeNumber() which takes a parameter num and returns a boolean value.
If the number is prime, it returns true. If not, it returns false.
Based on the return value, number is printed on the screen inside main() function.
Here's the equivalent Java code: Java Program to Check Prime Number using Function
Did you find this article helpful?