w3resource

Kotlin Function: Check Prime Number, Return Boolean


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.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax: Familiarity with writing and running Kotlin programs.
  • Kotlin Functions: Understanding how to define and call functions in Kotlin.
  • Explicit Return Types: Knowledge of specifying return types for functions, such as Boolean.
  • Conditional Statements: Ability to use if-else statements to handle different scenarios.
  • Loops in Kotlin: Knowledge of using for loops to iterate over a range of numbers.
  • Modulo Operator: Awareness of the modulo operator (%) to check divisibility.
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Handle Edge Cases.
  • Check Divisibility.
  • Return Early for Non-Primes.
  • Return True for Primes.
  • Call the Function.
  • Common Errors to Avoid:
    • Forgetting edge cases.
    • Misplacing modulo logic.
    • Not optimizing loop range.

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.