Skip to main content

How to check if a number is prime in Kotlin

How to check if a number is prime in Kotlin.

Here's a step-by-step tutorial on how to check if a number is prime in Kotlin.

Step 1: Understand Prime Numbers

Before we begin, let's briefly understand what prime numbers are. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, a prime number cannot be divided evenly by any other number except 1 and itself.

Step 2: Define a Function

To check if a number is prime, we can create a function that takes an integer as input and returns a boolean value indicating whether the number is prime or not.

fun isPrime(number: Int): Boolean {
// Code to check if the number is prime
}

Step 3: Handle Special Cases

Before we perform any calculations, let's handle a few special cases. Since prime numbers are greater than 1, we can return false if the input number is less than or equal to 1.

fun isPrime(number: Int): Boolean {
if (number <= 1) {
return false
}
// Code to check if the number is prime
}

Step 4: Check for Divisors

To determine if a number is prime, we need to check if it is divisible by any number from 2 to the square root of the number. If we find any divisor, the number is not prime.

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

for (i in 2..Math.sqrt(number.toDouble()).toInt()) {
if (number % i == 0) {
return false
}
}

return true
}

In the above code, we use a for loop starting from 2 (the smallest prime number) up to the square root of the input number. We use the Math.sqrt() function to calculate the square root and toInt() to convert it to an integer.

Inside the loop, we check if the number is divisible by i using the modulo operator (%). If the remainder is 0, it means the number is divisible and hence not prime. In that case, we return false.

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

Step 5: Test the Function

To ensure our function works correctly, let's test it with a few examples:

fun main() {
println(isPrime(2)) // true
println(isPrime(7)) // true
println(isPrime(10)) // false
println(isPrime(13)) // true
println(isPrime(16)) // false
}

When you run the above code, it should print true for the prime numbers (2, 7, and 13) and false for the non-prime numbers (10 and 16).

That's it! You now have a function that can check if a number is prime in Kotlin. Feel free to use this function in your projects or modify it as per your requirements.