Sha256: 963bb9155ab1b40d005c381c300638e2e784d733111785da918463179d545264

Contents?: true

Size: 601 Bytes

Versions: 219

Compression:

Stored size: 601 Bytes

Contents

import scala.annotation.tailrec

// Algorithm from - http://fldit-www.cs.uni-dortmund.de/~peter/PS07/HR.pdf
object PrimeFactors {
  def forNumber(n: Long): List[Long] = {
    assert(n >= 1, "Argument must be positive")

    @tailrec
    def primeAcc(n: Long, xs: List[Long]): List[Long] = {
      if (n == 1) xs
      else {
        val p = ld(n)
        primeAcc(n / p, p :: xs)
      }
    }

    primeAcc(n, List()).reverse
  }

  private def ld(n: Long) = ldf(2, n)

  @tailrec
  private def ldf(k: Long, n: Long): Long =
    if (n % k == 0) k
    else if (k * k > n) n
    else ldf(k + 1, n)
}


Version data entries

219 entries across 219 versions & 1 rubygems

Version Path
trackler-2.0.8.19 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.18 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.17 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.16 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.15 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.14 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.13 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.12 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.11 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.10 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.9 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.8 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.7 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.6 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.5 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.4 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.3 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.2 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.8.1 tracks/scala/exercises/prime-factors/example.scala
trackler-2.0.7.0 tracks/scala/exercises/prime-factors/example.scala