Kotlin Program to Check if a Number is Prime

In this blog post, we will learn how to write a Kotlin program to check if a number is Prime.

Determining whether a number is prime or not is a common problem in mathematics and programming. In this blog post, we will explore a Kotlin program that checks if a given number is prime. We will walk through the program step by step, explaining the logic behind it.

Kotlin Program to Check if a Number is Prime

To check if a number is prime in Kotlin, we can follow a straightforward approach. Let's dive into the code:

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() {
    val number = 29
    val isPrime = isPrime(number)

    if (isPrime) {
        println("$number is a prime number.")
    } else {
        println("$number is not a prime number.")
    }
}

Output:

29 is a prime number.
Explanation: 

The isPrime() function takes an integer number as input and returns a Boolean value indicating whether the number is prime. 

First, we check if the number is less than or equal to 1. Since prime numbers are greater than 1, any number less than or equal to 1 is not prime. In such cases, we immediately return false

Next, we loop through the numbers from 2 to number - 1 using the for loop. We check if the number is divisible by any of these numbers. If it is, the number is not prime, and we return false. 

If the loop completes without finding any divisors, the number is prime, and we return true

In the main() function, we create a sample input number (val number = 29) and call the isPrime() function with this number. The function's result is stored in the isPrime variable, and we use an if-else statement to print whether the number is prime or not. 

Conclusion

In this blog post, we have discussed a Kotlin program that checks if a given number is prime. By implementing a straightforward algorithm that checks for divisors, we can efficiently determine the primality of a number. Understanding this program equips you with the necessary skills to identify prime numbers and solve similar mathematical problems in Kotlin. 

Feel free to explore and modify the code to suit your specific needs. The ability to check for prime numbers is a fundamental skill in programming and mathematics. Happy coding!

Comments