Kotlin Program to Display Prime Numbers Between Intervals Using Function

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?