I am new to Scala, just wrote this program:
def isPrime(num: Int, primes: scala.collection.mutable.MutableList[Int]): Boolean = {
primes.takeWhile( i => i * i <= num).forall( num % _ > 0)
}
//def isPrime(num: Int, primes: scala.collection.mutable.MutableList[Int]): Boolean = {
// !primes.forall(num%_!=0)
//}
def primeListUnder(upper: Int) = {
val primes=scala.collection.mutable.MutableList(2,3);
var num=4
while(num<upper) {
if(isPrime(num,primes))
{
primes+=num
}
num+=1
}
primes
}
This is trying to get all the prime numbers under some specified upper bound. But it runs really slow. Any suggestions?
Added: Actually my point is to know why this program runs so slow. It's not about how to calc the prime numbers.
Edit: Changed the isPrime method to first filter out some numbers (mathematically). Now is runs much faster, takes about 10 secs on my mac to count to 2000000;