生成一个数的素因数的scala方法 [英] scala way to generate prime factors of a number

查看:54
本文介绍了生成一个数的素因数的scala方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生成整数因子的 Scala 方法是什么?这是我的看法 1:

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)//列表(2, 2, 2, 3, 3, 5)

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

Take 2 基于@SpiderPig 和@seth-tisue 的评论

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)
}

推荐答案

尾递归解决方案:

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)
}

这篇关于生成一个数的素因数的scala方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆