寻找一些代码示例以使用 while 循环找出给定数字是否为质数。我知道我可以使用以下函数,但我需要在这个练习中使用一个 while 循环。
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)))
Run Code Online (Sandbox Code Playgroud)
以下代码应该可以解决您的问题,但我建议您阅读一些我稍后会添加的注释:
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")
}
Run Code Online (Sandbox Code Playgroud)
笔记:
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)