0

我一直在尝试在 Scala中解决 3 中的项目欧拉数,这就是我到目前为止所得到的:

def largestPrimeFactor(in:BigInt) : Option[BigInt] = {
  def isPrime(in:BigInt) : Boolean = {
    def innerIsPrime(in:BigInt, currentFactor:BigInt) : Boolean = {
        if(in % currentFactor == 0) {
        false
      }
      else {
        if(currentFactor > (in / 2)){
           true
        }
        else {
          innerIsPrime(in, currentFactor + 1)
        }
      }
    }

     innerIsPrime(in, 2)
  }

   def nextLargeFactor(in:BigInt, divisor:BigInt) : (Option[BigInt], BigInt) = {
     if((in / 2) > divisor) {
       if(in % divisor == 0) (Some(in / divisor), divisor) 
       else nextLargeFactor(in, divisor + 1)
     }
     else
       (None, divisor)
   }

   def innerLargePrime(in : BigInt, divisor:BigInt) : (Option[BigInt], BigInt) = {
     nextLargeFactor(in, divisor) match {
       case (Some(factor), div) => {
         if(isPrime(factor)) (Some(factor), div)
         else innerLargePrime(in, div + 1)
       }
       case (None, _) => (None, divisor)
     }
  }

  innerLargePrime(in, 2)._1
}

我认为这会起作用,但我被困在工作中(在缓慢的构建过程中利用时间)并且只有 SimplyScala 服务——它正在超时(我会在家里检查它)。

但由于这是我写的任何长度的 Scala 的第一部分,我想我会问,我犯了哪些可怕的罪行?我的解决方案是多么不理想?我践踏了哪些约定?

谢谢!

4

2 回答 2

9

我真的不明白你试图完成什么。就这么简单:

def largestPrimeFactor(b : BigInt) = {
  def loop(f:BigInt, n: BigInt): BigInt =
     if (f == n) n else 
     if (n % f == 0) loop(f, n / f) 
     else loop(f + 1, n)
  loop (BigInt(2), b)
}

虽然这里没有优化,但我立即得到结果。唯一的“技巧”是您必须知道数字的最小因子(较大的因子)是“自动”素数,并且一旦找到因子就可以除以该数字。

于 2011-01-20T13:49:49.760 回答
1

取自这里

lazy val ps: Stream[Int] =
  2 #:: ps.map(i =>
    Stream.from(i + 1).find(j =>
      ps.takeWhile(k => k * k <= j).forall(j % _ > 0)
    ).get
)

val n = 600851475143L
val limit = math.sqrt(n)
val r = ps.view.takeWhile(_ < limit).filter(n % _ == 0).max

r 是你的答案

于 2011-02-18T13:24:42.507 回答