Scala way to generate prime factors of a number

What is scala's way of generating integer multipliers? Here's my example 1:

def factorize(x: Int): List[Int] = {

  def foo(x: Int, a: Int): List[Int] = {

    if (a > Math.pow(x, 0.5))
      return List(x)

    x % a match {
      case 0 => a :: foo(x / a, a)
      case _ => foo(x, a + 1)
    }
  }

  foo(x, 2)
}

      

factorize (360) // List (2, 2, 2, 3, 3, 5)

Take 2 based on @SpiderPig and @ seth-tisue comments

def factorize(x: Int): List[Int] = {
  def foo(x: Int, a: Int): List[Int] = {
    (a*a < x, x % a) match {
        case (true, 0) => a :: foo(x/a, a)
        case (true, _) => foo(x, a+1)
        case (false, _) => List(x)
      }
  }
  foo(x, 2)
}

      

+3


source to share


2 answers


Recursive tail solution:



def factorize(x: Int): List[Int] = {
  @tailrec
  def foo(x: Int, a: Int = 2, list: List[Int] = Nil): List[Int] = a*a > x match {
    case false if x % a == 0 => foo(x / a, a    , a :: list)
    case false               => foo(x    , a + 1, list)
    case true                => x :: list
  }
  foo(x)
}

      

+5


source


Just a slight improvement "Take 2" from the question:

def factorize(x: Int): List[Int] = {
  def foo(x: Int, a: Int): List[Int] = x % a match {
     case _ if a * a > x  => List(x)
     case 0 => a :: foo(x / a, a)
     case _ => foo(x, a + 1)
  }
  foo(x, 2)
}

      



Also, the following method might be slightly faster (computed x % a

in the last iteration):

def factorize(x: Int): List[Int] = {
  def foo(x: Int, a: Int): List[Int] = if (a * a > x) List(x) else
    x % a match {
      case 0 => a :: foo(x / a, a)
      case _ => foo(x, a + 1)
    }
  foo(x, 2)
}

      

0


source







All Articles