1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scalaで素数のサンプル

1
Last updated at Posted at 2018-04-01

少し古いがこちらを参考に。

Scala 2.12.4
object PrimeNumber {
  // 約数を求める
  def divisors(n: Int): List[Int] =
    for (i <- (1 to n).toList if n % i == 0) yield i

  // 約数が2のときは素数
  def isPrime(n: Int): Boolean = divisors(n).lengthCompare(2) == 0

  // 与えられた整数までの素数のリストを返す
  def findPrimeUntil(n: Int): Iterable[Int] = {
    for (i <- 1 to n if isPrime(i)) yield i
  }

  def main(args: Array[String]) {
    val l = findPrimeUntil(30)
    println(l)
  }
}
// Vector(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?