Find prime numbers using Scala. Help me to improve

前端 未结 10 960
北荒
北荒 2020-12-01 22:31

I wrote this code to find the prime numbers less than the given number i in scala.

def findPrime(i : Int) : List[Int] = i match {
    case 2 => List(2)
           


        
10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 22:35

    Here's a functional implementation of the Sieve of Eratosthenes, as presented in Odersky's "Functional Programming Principles in Scala" Coursera course :

      // Sieving integral numbers
      def sieve(s: Stream[Int]): Stream[Int] = {
        s.head #:: sieve(s.tail.filter(_ % s.head != 0))
      }
    
      // All primes as a lazy sequence
      val primes = sieve(Stream.from(2))
    
      // Dumping the first five primes
      print(primes.take(5).toList) // List(2, 3, 5, 7, 11)
    

提交回复
热议问题