euler项目总和和Stream.view

时间:2011-02-28 00:19:19

标签: scala

http://pavelfatin.com/scala-for-project-euler/查看项目Euler解决方案时,我对“问题10”的解决方案中的视图如何处理感到有些困惑 计算所有素数低于200万的总和。“

建议的解决方案是:

lazy val ps: Stream[Int] = 2 #:: ps.map(i => Stream.from(i + 1).find(
    j => ps.takeWhile(k => k * k <= j).forall(j % _ > 0)).get)
val r = ps.view.takeWhile(_ < 2000000).foldLeft(0L)(_ + _)

...导致142913828922

如果您遗漏视图,我注意到您得到了不同的结果1179908154

val r = ps.takeWhile(_ < 2000000).foldLeft(0L)(_ + _)

有人可以向我解释为什么这些不同吗?

1 个答案:

答案 0 :(得分:0)

Welcome to Scala version 2.8.1.final (Java HotSpot(TM) Client VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.

scala> lazy val ps: Stream[Int] = 2 #:: ps.map(i => Stream.from(i + 1).find(
     |     j => ps.takeWhile(k => k * k <= j).forall(j % _ > 0)).get)
ps: Stream[Int] = <lazy>

scala> val r = ps.view.takeWhile(_ < 2000000).foldLeft(0L)(_ + _)
r: Long = 142913828922

scala> val r = ps.takeWhile(_ < 2000000).foldLeft(0L)(_ + _)
r: Long = 142913828922