Find prime numbers using Scala. Help me to improve

前端 未结 10 956
北荒
北荒 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:55

      /**
       * @return Bitset p such that p(x) is true iff x is prime
       */
      def sieveOfEratosthenes(n: Int) = {
        val isPrime = mutable.BitSet(2 to n: _*)
        for (p <- 2 to Math.sqrt(n) if isPrime(p)) {
          isPrime --= p*p to n by p
        }
        isPrime.toImmutable
      }
    

提交回复
热议问题