scala: 使用while循环检查是否为质数

huangapple go评论74阅读模式
英文:

scala: check if a prime number using a while loop

问题

寻找一些代码示例,以使用 while 循环判断给定的数字是否是质数。
我知道我可以使用以下函数,但我需要使用 while 循环来完成此练习。

def isPrimeWithWhile(num: Int): Boolean = {
  if (num <= 1) {
    false
  } else if (num <= 3) {
    true
  } else {
    var i = 2
    while (i * i <= num) {
      if (num % i == 0) {
        return false
      }
      i += 1
    }
    true
  }
}

(1 to 20).foreach { i =>
  if (isPrimeWithWhile(i)) println(s"$i is prime")
}
英文:

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 =&gt; num % x != 0)

(1 to 20).foreach(i =&gt; if (isPrime5(i)) println(&quot;%d is prime5&quot;.format(i)))

答案1

得分: 6

以下是翻译好的代码部分:

以下代码应该解决了您的问题但我建议您阅读之后我将添加的一些注释

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 是素数")
}

注释:

  1. 这是将您的代码使用 while 循环进行一对一的移植;请注意存在一个错误(即,1 不是素数)。
  2. 我将您打印从 1 到 20 的素数的“测试”重构为 for 推导式。
  3. 在 Scala 世界中,诸如可变性、while 循环和早期返回之类的命令式构造通常是最后的选择,仅用于对特定问题有益于使用这种方法的情况(开发人员可以自行评估何时使用此方法有意义)。
  4. 特别地,在 Scala 中使用 return 可能会导致与使用更广泛接受的返回机制产生语义差异,即让方法的最后一个表达式定义方法本身的返回值(更多信息请参阅此处)。

请注意,我只翻译了代码和注释部分,不包括其他内容。

<details>
<summary>英文:</summary>

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

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

    for (n &lt;- 1 to 20 if isPrime(n)) {
      println(s&quot;$n is prime&quot;)
    }

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)
1. I refactored the &quot;test&quot; where you print the primes from 1 to 20 into a for-comprehension
1. 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)
1. 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][1])


  [1]: https://tpolecat.github.io/2014/05/09/return.html

</details>



huangapple
  • 本文由 发表于 2020年1月6日 19:18:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611159.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定