Find prime numbers using Scala. Help me to improve

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

    As schmmd mentions, you want it to be tail recursive, and you also want it to be lazy. Fortunately there is a perfect data-structure for this: Stream.

    This is a very efficient prime calculator implemented as a Stream, with a few optimisations:

    object Prime {
      def is(i: Long): Boolean =
        if (i == 2) true
        else if ((i & 1) == 0) false // efficient div by 2
        else prime(i)
    
      def primes: Stream[Long] = 2 #:: prime3
    
      private val prime3: Stream[Long] = {
        @annotation.tailrec
        def nextPrime(i: Long): Long =
          if (prime(i)) i else nextPrime(i + 2) // tail
    
        def next(i: Long): Stream[Long] =
          i #:: next(nextPrime(i + 2))
    
        3 #:: next(5)
    
      }
    
        // assumes not even, check evenness before calling - perf note: must pass partially applied >= method
      def prime(i: Long): Boolean =
        prime3 takeWhile (math.sqrt(i).>= _) forall { i % _ != 0 }
    }
    

    Prime.is is the prime check predicate, and Prime.primes returns a Stream of all prime numbers. prime3 is where the Stream is computed, using the prime predicate to check for all prime divisors less than the square root of i.

提交回复
热议问题