English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program using functions to display prime numbers between intervals

Comprehensive Collection of Kotlin Examples

In this program, you will learn to use Kotlin functions to display all prime numbers within a given range.

To find all prime numbers between two integers, the function checkPrimeNumber() will be created. This functionCheck if a number is a prime number.

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 the program is run, the output is:

23 29 31 37 41 43 47

In the above program, we created a function named checkPrimeNumber() that accepts a parameter num and returns a boolean value.

If the number is a prime number, it returns true. If not, it returns false.

Based on the return value, the number will be printed on the screen inside the main() function.

This is the equivalent Java code:Java Program to Check for Prime Numbers Using Functions

Comprehensive Collection of Kotlin Examples