w3resource

Kotlin Function: Check Prime Number, Return Boolean

Kotlin Function: Exercise-17 with Solution

Write a Kotlin function that takes an integer as an argument and returns a Boolean indicating whether the number is prime or not. Use explicit return type.

Sample Solution:

Kotlin 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 = 13
    val isNumberPrime = isPrime(number)
    println("Is $number a prime number? $isNumberPrime")
}

Sample Output:

Is 13 a prime number? True

Explanation:

In the above exercise -

  • The "isPrime()" function, receives a number parameter of type Int.
  • Check if the number is less than or equal to 1, in which case it's not prime, and return false.
  • Then, iterate from 2 to one less than the number and check if any number divides the given number without leaving a remainder.
  • If find such a divisor, return false, indicating that the number is not prime.
  • If the loop ends without finding any divisors, return true, indicating that the number is prime.
  • In the "main()" function, we call the "isPrime()" function with a sample number (in this case, 13) and store the result in isNumberPrime. Finally, we print whether the number is prime or not using println.

Kotlin Editor:


Previous: Add two numbers with an explicit return type.
Next: Calculate the average of variable number of arguments.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.