首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >查找给定数字中每一个数字的乘积

查找给定数字中每一个数字的乘积
EN

Stack Overflow用户
提问于 2020-01-08 19:01:49
回答 1查看 70关注 0票数 1

在scala中,我需要编写一个方法来查找给定数字中每个数字的乘积。我有下面的片段。

代码语言:javascript
复制
  def productDigits(number: Int): Int = {
    def helper(current: Int, accumulator: Int): Int = {
      current match {
        case current if current < 10 => accumulator * current
        case _ => helper(current / 10, accumulator * (current % 10))
      }
    }
    helper(number, 1)
  }

有更好的方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-08 19:36:13

下面是OP递归解决方案的jmh基准与Luis‘one-liner的比较。

执行

sbt "jmh:run -i 10 -wi 10 -f 2 -t 1 bench.So59652263"

哪里

代码语言:javascript
复制
@State(Scope.Benchmark)
@BenchmarkMode(Array(Mode.Throughput))
class So59652263 {
  def _dexter2305(number: Int): Int = {
    def helper(current: Int, accumulator: Int): Int = {
      current match {
        case current if current < 10 => accumulator * current
        case _ => helper(current / 10, accumulator * (current % 10))
      }
    }
    helper(number, 1)
  }

  def _luis(number: Int): Int = number.toString.map(_.asDigit).product

  val num: Int = (math.random * 100000000).toInt
  @Benchmark def dexter2305: Int = _dexter2305(num)
  @Benchmark def luis: Int = _luis(num)
}

给出

代码语言:javascript
复制
[info] So59652263.dexter2305  thrpt   20  89093066.408 ± 1825286.801  ops/s
[info] So59652263.luis        thrpt   20  11585098.230 ±  272966.526  ops/s

在我们所看到的递归解决方案中,似乎比一行程序的吞吐量高出7倍。

numberString而不是Int时进行基准测试

代码语言:javascript
复制
@State(Scope.Benchmark)
@BenchmarkMode(Array(Mode.Throughput))
class So59652263 {
  def _dexter2305(number: String): Int = {
    def helper(current: Int, accumulator: Int): Int = {
      current match {
        case current if current < 10 => accumulator * current
        case _ => helper(current / 10, accumulator * (current % 10))
      }
    }
    helper(number.toInt, 1)
  }

  def _luis(number: String): Int = number.map(_.asDigit).product

  val num: String = (math.random * 100000000).toInt.toString
  @Benchmark def dexter2305: Int = _dexter2305(num)
  @Benchmark def luis: Int = _luis(num)
}

给出

代码语言:javascript
复制
[info] Benchmark               Mode  Cnt         Score         Error  Units
[info] So59652263.dexter2305  thrpt   20  36237007.844 ± 1631349.975  ops/s
[info] So59652263.luis        thrpt   20  13975984.042 ± 1890083.941  ops/s

但是,递归解决方案的吞吐量仍然比numberInt时小2.5倍。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59652263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档