scala way to generate prime factors of a number

僤鯓⒐⒋嵵緔 提交于 2021-02-19 04:37:12

问题


What's the scala way to generate the factors of an integer? Here's my take 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's 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)
}

回答1:


A tail recursive 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)
}



回答2:


Just little improvement of "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 may be a little faster (no x % a calculation 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)
}


来源:https://stackoverflow.com/questions/30280524/scala-way-to-generate-prime-factors-of-a-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!