相关疑难解决方法(0)

使用Scala查找素数.帮助我改进

我写了这段代码,以便在scala中找到小于给定数字i的素数.

def findPrime(i : Int) : List[Int] = i match {
    case 2 => List(2)
    case _ => {
    val primeList = findPrime(i-1)
    if(isPrime(i, primeList)) i :: primeList else primeList
    }
}

def isPrime(num : Int, prePrimes : List[Int]) : Boolean = prePrimes.forall(num % _ != 0)    
Run Code Online (Sandbox Code Playgroud)

但是,我感觉findPrime函数,特别是这部分:

case _ => {
    val primeList = findPrime(i-1)
    if(isPrime(i, primeList)) i :: primeList else primeList
}
Run Code Online (Sandbox Code Playgroud)

不是功能风格.

我还在学习函数式编程.任何人都可以帮我改进这个代码,使其更具功能性.

非常感谢.

algorithm primes functional-programming scala

5
推荐指数
3
解决办法
1万
查看次数

标签 统计

algorithm ×1

functional-programming ×1

primes ×1

scala ×1