Write a Kotlin Program to Check Whether a Number is Prime or Not

In Kotlin, we can easily check whether a given number is prime or not using a simple algorithm.

A prime number is a number that is divisible only by 1 and itself.

In other words, a prime number has no other factors except 1 and itself.

To check if a number is prime or not, we need to check if it is divisible by any number from 2 to (n-1), where n is the given number.

If the number is not divisible by any of these numbers, then it is a prime number.

Here’s a Kotlin program to check whether a number is prime or not:

fun isPrime(n: Int): Boolean {
    if (n <= 1) return false // 1 is not a prime number
    for (i in 2..(n-1)) {
        if (n % i == 0) return false
    }
    return true
}

In this program, we define a function isPrime that takes an integer argument n and returns a boolean value indicating whether n is a prime number or not.

The first line of the function checks if n is less than or equal to 1. If it is, then we return false, since 1 is not a prime number.

The next part of the function is a loop that iterates from 2 to (n-1).

For each value of i in this range, we check if n is divisible by i using the modulus operator %. If n is divisible by i, then we return false, since n is not a prime number.

If the loop completes without finding any divisors of n, then we can conclude that n is a prime number, so we return true.

Here’s an example of how to use the isPrime function:

fun main() {
    val n = 17
    if (isPrime(n)) {
        println("$n is a prime number")
    } else {
        println("$n is not a prime number")
    }
}

In this example, we call the isPrime function with the value 17, which is a prime number.

The program will print the message “17 is a prime number” to the console.

If we called the isPrime function with a non-prime number like 20, the program would print the message “20 is not a prime number” instead.

That’s it! With this simple algorithm and Kotlin code, we can easily check whether a given number is prime or not.