Reputation: 45
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
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:
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)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