euler project sum-of-primes, and Stream.view

2019-08-13 02:07发布

问题:

Looking at the Project Euler solutions at http://pavelfatin.com/scala-for-project-euler/, I got a bit confounded by how a view comes in to play in the solution for "Problem 10 Calculate the sum of all the primes below two million."

The proposed solution is:

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)(_ + _)

...which results in 142913828922

I noticed you get a different result, 1179908154, if you leave out the view:

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

Can someone explain to me why these are different?

回答1:

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


标签: scala