欧拉项目素数和,以及 Stream.view

发布于 2024-10-19 18:14:51 字数 674 浏览 2 评论 0原文

查看 Project Euler 解决方案 http://pavelfatin.com/scala-for-project- 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)(_ + _)

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暖风昔人 2024-10-26 18:14:51
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
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文