w3resource

Scala function: Determine if a number is prime


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


Pre-Knowledge (Before you start!)

  • Understanding of basic programming concepts like variables, loops, and conditional statements.
  • Familiarity with Scala syntax, including functions, return statements, and the main method.
  • Knowledge of prime numbers: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
  • Understanding of mathematical operations like modulus (%) and comparison operators (<=, ==, etc.).
  • Basic understanding of optimization techniques, such as checking divisibility only up to the square root of the number.

Hints (Try before looking at the solution!)

  • Start by handling edge cases: Numbers less than or equal to 1 are not prime, and numbers 2 and 3 are prime.
  • Check divisibility by 2 and 3 first, as these are the smallest prime numbers and can quickly eliminate non-prime numbers.
  • For numbers greater than 3, use a loop to check divisibility starting from 5 and increment by 6 (since primes greater than 3 are of the form 6k ± 1).
  • Optimize the loop by only checking divisibility up to the square root of the number, as factors larger than the square root would have already been checked.
  • Use the return statement to exit the function early if a divisor is found.
  • Print the result in the main method based on the return value of the isPrime function.

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?



Follow us on Facebook and Twitter for latest update.