In this tutorial, you shall learn how to write a program to check if given number is a prime number in Kotlin.

Kotlin – Check Prime Number

To check if given number is a prime number in Kotlin, check if there is any factor other than 1 and itself. If there is one, then given number is not a prime number.

Program

In the following program, we read a number from user and store it in num, then check if this number is a Prime number or not.

We write a function isPrime() that takes an integer as an argument, and returns a boolean value of true if the given number is Prime number, or false otherwise.

Main.kt

fun isPrime(number: Int): Boolean {
    if (number <= 1) {
        return false
    }

    for (i in 2 until number) {
        if (number % i == 0) {
            return false
        }
    }

    return true
}

fun main() {
    print("Enter an integer : ")
    val num = readLine()!!.toInt()
    if ( isPrime(num) ) {
        println("$num is a prime number")
    } else {
        println("$num is not a prime number")
    }
}

Output #1

Enter an integer : 17
17 is a prime number

Output #2

Enter an integer : 42
42 is not a prime number

Related tutorials for the above program

ADVERTISEMENT

Program with Increased Performance

We can increase the performance of isPrime() function to take less iterations to check if the given number is Prime number or not. Instead of checking from i=2 to number, we can check from i=2 to number/i because if 2 is not a factor of the given number, then there is no factor between [number/2, number]. We take this fact into consideration and modify the For loop to a While loop.

Main.kt

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 an integer : ")
    val num = readLine()!!.toInt()
    if ( isPrime(num) ) {
        println("$num is a prime number")
    } else {
        println("$num is not a prime number")
    }
}

Output #1

Enter an integer : 17
17 is a prime number

Output #2

Enter an integer : 42
42 is not a prime number

Related tutorials for the above program

Conclusion

In this Kotlin Tutorial, we learned how to check if given number is a Prime number or not.