// // program to compute primes <= n using sieve of Eratosthenes // import scala.io.StdIn._ println("largest number to try?") val n = readInt // // isPrime(i) will be true if i is prime, false otherwise // val isPrime = Array.fill(n+1)(true) isPrime(0) = false isPrime(1) = false // initially i ranged from 2 to n, but we can do better: // any non-prime will have at least one prime factor <= sqrt(n) for (i <- 2 to math.ceil(math.sqrt(n)).toInt) { if (isPrime(i)) { // "cross out" multiples of i println("crossing out multiples of "+i) for (j <- i*2 to n by i) { if (isPrime(j)) println("crossing out "+j) isPrime(j) = false } } } println() println("primes:") for (i <- 0 to n) { if (isPrime(i)) println(i) }