29 lines
862 B
Scala
29 lines
862 B
Scala
// Scala primes
|
|
// This to my mind may not be the fastest algorithm,
|
|
// I would think printing when finding would be better,
|
|
// especially on memory, then storing the thing in a list
|
|
// and then running mkString on it, but it already
|
|
// outperforms java for me, so here it is
|
|
|
|
object Primes {
|
|
def main(args: Array[String]) {
|
|
if (args.length < 1) {
|
|
println("Usage: scala Primes [MAX]")
|
|
} else print(primes(3, List(), args(0).toInt).mkString("\n") + "\n")
|
|
}
|
|
|
|
def is_prime(num: Int): Boolean = {
|
|
def prime_loop(i: Int, max: Int): Boolean =
|
|
if (i > max) true
|
|
else if (num % i == 0) false
|
|
else prime_loop(i+2, max)
|
|
prime_loop(3, scala.math.sqrt(num).ceil.toInt)
|
|
}
|
|
|
|
def primes(i: Int, acc: List[Int], max: Int): List[Int] =
|
|
if (i >= max) acc
|
|
else if (is_prime(i)) primes(i+2, acc ++ List(i), max)
|
|
else primes(i+2, acc, max)
|
|
|
|
}
|