欧拉项目素数和,以及 Stream.view
查看 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)