Find prime numbers using Scala. Help me to improve

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

    A scalar fp approach

    // returns the list of primes below `number`
    def primes(number: Int): List[Int] = {
        number match {
            case a
            if (a <= 3) => (1 to a).toList
            case x => (1 to x - 1).filter(b => isPrime(b)).toList
        }
    }
    
    // checks if a number is prime
    def isPrime(number: Int): Boolean = {
        number match {
            case 1 => true
            case x => Nil == {
                2 to math.sqrt(number).toInt filter(y => x % y == 0)
            }
        }
    }
    

提交回复
热议问题