fork(1) download
  1. import scala.collection.immutable.Queue
  2. import scala.annotation.tailrec
  3.  
  4. object Main extends App {
  5.  
  6. var t = System.currentTimeMillis
  7.  
  8. def primes(n: Int) = {
  9. @tailrec
  10. def divisibleByAny(x: Int, list: Vector[Int]): Boolean = {
  11. if (list.isEmpty) false else {
  12. val (h +: t) = list
  13. h * h <= x && (x % h == 0 || divisibleByAny(x, t))
  14. }
  15. }
  16. @tailrec
  17. def morePrimes(from: Int, prev: Vector[Int]): Vector[Int] = {
  18. if (prev.length == n) prev else
  19. morePrimes(from + 2, if (divisibleByAny(from, prev)) prev else prev :+ from)
  20. }
  21. morePrimes(3, Vector(2))
  22. }
  23.  
  24.  
  25.  
  26. System.out.println(primes(3000).last);
  27. t = System.currentTimeMillis - t
  28. System.out.println(t + "ms");
  29.  
  30. }
Success #stdin #stdout 0.47s 322176KB
stdin
Standard input is empty
stdout
27449
230ms