fork(2) 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: List[Int]): Boolean = {
  11. if (list.isEmpty) false else {
  12. val h = list.head
  13. h * h <= x && (x % h == 0 || divisibleByAny(x, list.tail))
  14. }
  15. }
  16. @tailrec
  17. def morePrimes(from: Int, prev: List[Int]): List[Int] = {
  18. if (prev.size == n) prev else
  19. morePrimes(from + 2, if (divisibleByAny(from, prev)) prev else prev :+ from)
  20. }
  21. morePrimes(3, List(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 1.89s 322176KB
stdin
Standard input is empty
stdout
27449
1632ms