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 に答える