sid
sid

Reputation: 45

scala: check if a prime number using a while loop

Looking for some code sample to find out whether a given number is a prime number or not using a while loop. I know I can use the following function but I need to use a while loop for this exercise.

def isPrime5(num: Int): Boolean =
  (2 to math.sqrt(num).toInt) forall(x => num % x != 0)

(1 to 20).foreach(i => if (isPrime5(i)) println("%d is prime5".format(i)))

Upvotes: 0

Views: 474

Answers (1)

stefanobaghino
stefanobaghino

Reputation: 12804

The following code should solve your problem, but I would suggest you read a few notes I'll add afterwards:

def isPrime(num: Int): Boolean = {
  var n = 2
  val threshold = math.sqrt(num)
  while (n <= threshold) {
    if (num % n == 0) {
      return false
    }
    n += 1
  }
  return true
}

for (n <- 1 to 20 if isPrime(n)) {
  println(s"$n is prime")
}

Notes:

  1. This is a one-to-one porting of your code using a while loop; please note there is a bug (namely, 1 is not a prime number)
  2. I refactored the "test" where you print the primes from 1 to 20 into a for-comprehension
  3. Imperative constructs like mutability, while loops and early returns are generally used as a last resort in the Scala world, for very specific problems that can benefit from using this approach (the developer is free to evaluate when this makes sense)
  4. In particular, using return in Scala can lead to semantic differences from using the more widely accepted return mechanism of letting the last expression of a method define the return value of the method itself (more on this here)

Upvotes: 6

Related Questions