Kotlin Program to Display Prime Numbers Between Two Intervals

Example: Display Prime Numbers Between two Intervals

fun main(args: Array<String>) {
    var low = 20
    val high = 50

    while (low < high) {
        var flag = false

        for (i in 2..low / 2) {
            // condition for nonprime number
            if (low % i == 0) {
                flag = true
                break
            }
        }

        if (!flag)
            print("$low ")

        ++low
    }
}

When you run the program, the output will be:

23 29 31 37 41 43 47 

In this program, each number between low and high are tested for prime. The inner for loop checks whether the number is prime or not.

You can check: Kotlin Program to Check Prime Number for more explanation.

The difference between checking a single prime number compared to an interval is, you need to reset the value of flag = false on each iteration of while loop.

Did you find this article helpful?