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.1.0.24 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.23 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.22 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.21 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.20 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.19 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.18 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.17 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.16 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.15 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.14 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.13 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.12 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.11 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.10 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.9 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.8 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.7 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.6 tracks/scala/exercises/prime-factors/example.scala
trackler-2.1.0.5 tracks/scala/exercises/prime-factors/example.scala