fork 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: Queue[Int]): Boolean = {
  11. if (list.isEmpty) false else {
  12. val (h, t) = list.dequeue
  13. h * h <= x && (x % h == 0 || divisibleByAny(x, t))
  14. }
  15. }
  16. @tailrec
  17. def morePrimes(from: Int, prev: Queue[Int]): Queue[Int] = {
  18. if (prev.size == n) prev else
  19. morePrimes(from + 2, if (divisibleByAny(from, prev)) prev else prev.enqueue(from))
  20. }
  21. morePrimes(3, Queue(2))
  22. }
  23.  
  24. System.out.println(primes(3000).last);
  25. t = System.currentTimeMillis - t
  26. System.out.println(t + "ms");
  27.  
  28. }
Success #stdin #stdout 2.64s 322176KB
stdin
Standard input is empty
stdout
27449
2375ms