w3resource

Kotlin recursive function: Check prime number

Kotlin Function: Exercise-8 with Solution

Write a Kotlin recursive function to check if a number is a prime number.

Sample Solution:

Kotlin Code:

fun isPrime(n: Int, current: Int = 2): Boolean {
    if (n <= 1) {
        return false
    }

    if (current * current > n) {
        return true
    }

    if (n % current == 0) {
        return false
    }

    return isPrime(n, current + 1)
}

fun main() {
    val number = 37
    //val number = 38
    val isPrimeNumber = isPrime(number)
    val message = if (isPrimeNumber) "is a prime number." else "is not a prime number."
    println("$number $message")
}

Sample Output:

37 is a prime number.
38 is not a prime number.

Explanation:

In the above exercise -

The "isPrime()" function takes two parameters: n (the number to check for primality) and current (the current divisor being tested, initialized to 2).

To determine whether n is prime, the function uses recursion. It follows the following steps:

  • Since prime numbers are greater than 1, it returns false if n is less than or equal to 1.
  • If the square of current is greater than n, it means we have tested all possible divisors up to the square root of n, and none of them divided n evenly. Thus, n is a prime number, and the function returns true.
  • If n is divisible evenly by the current divisor, it means n is not a prime number. The function returns false.
  • Otherwise, it calls itself recursively with the same n but increments the current divisor by 1.

In the "main()" function, we define number's value as 37 to check if it's a prime number. We call the "isPrime()" function with this number and store the result in the isPrimeNumber variable. The result is then printed to the console.

Kotlin Editor:


Previous: Find the nth term of arithmetic sequence.
Next: Print even numbers from an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/kotlin-exercises/recursion-function/kotlin-recursion-function-exercise-8.php