w3resource

Scala function: Determine if a number is prime

Scala Function Exercise-2 with Solution

Write a Scala function to check if a given number is prime.

Sample Solution:

Scala Code:

object PrimeChecker {
  def isPrime(n: Int): Boolean = {
    if (n <= 1) {
      false
    } else if (n <= 3) {
      true
    } else if (n % 2 == 0 || n % 3 == 0) {
      false
    } else {
      var i = 5
      while (i * i <= n) {
        if (n % i == 0 || n % (i + 2) == 0) {
          return false
        }
        i += 6
      }
      true
    }
  }

  def main(args: Array[String]): Unit = {
    val number = 13
    val isPrimeNumber = isPrime(number)
    if (isPrimeNumber) {
      println(s"$number is prime.")
    } else {
      println(s"$number is not prime.")
    }
  }
}

Sample Output:

13 is prime

Scala Code Editor :

Previous: Calculate the factorial of a number.
Next: Calculate the sum of digits in a number.

What is the difficulty level of this exercise?



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/scala-exercises/function/scala-function-exercise-2.php