I'm trying to implement the Sieve of Eratosthenes in Scala.
I start by initializing a sequence of all odd numbers plus 2:
// (end goal is to find all prime factors of bigNumber)
val largestPrime : Long = Math.ceil(Math.sqrt(bigNumber)).toLong
var nums : Seq[Long] = (3L to largestPrime by 2L).toSeq
nums +: 2L
Now nums
contains Seq( 2,3,5,7,9,11,13,15,...,(largestPrime) ). Then, by the Sieve, I want to iterate over each element, and filter all multiples of that element from the Seq. It would look something like this, except this simply iterates over every odd number:
for(i : Long <- 3L to largestPrime by 2L) {
nums = nums.filter((j : Long) => j == i || j % i != 0)
}
So instead, I would want to use something like this:
for(i <- nums) {
// filter
}
But of course, this simply copies the sequence into an iterator and then iterates over every value in nums
as it was at the beginning of the for loop (so in this case, it's exactly equivalent to the previous example). I want it to, every iteration, grab the next value from nums
.
How is the best way to implement this? Should I use an index variable and a while loop? I'm not sure how to get an element from a sequence (i.e. how to get element x of the sequence, where x is the index). Or is there a more functional way to do this?
Edit: I just found the scanLeft
function, I'm trying to grasp how to use it as I suspect it might be of use in this case...