Euler project of sums of primes and Stream.view

Looking at Project Euler solutions at http://pavelfatin.com/scala-for-project-euler/ , I was a little embarrassed by what the view in the solution to "Problem 10 looks like. Calculate the sum of all primes below two million.

Proposed Solution:

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 leads to 142913828922

I noticed that you got a different result, 1179908154 , if you do not take the view into account:

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

Can someone explain to me why they are different?

+1
source share
1 answer
 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 
0
source

Source: https://habr.com/ru/post/1391579/


All Articles