Crible d’Ératosthène en Scala

Le crible d’Ératosthène est un grand classique des langages fonctionnels :

def primes (end: Int): Seq[Int] = {
  def sieve (list: Seq[Int]): Seq[Int] = {
    list match {
      case Nil => List()
      case x :: xs => List(x) ++ sieve(xs.filter(_ % x != 0))
    }
  }
  sieve(List.range(2, end))
}

Faisons un test :

scala> primes(100)
res0: Seq[Int] = List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
This entry was posted in Du code, rien que du code and tagged . Bookmark the permalink.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*


+ quatre = 5

Vous pouvez utiliser ces balises et attributs HTML : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">