fork download
  1. object Main {
  2. /**
  3.   * Checks if a number is prime using optimized trial division
  4.   * @param n The number to check
  5.   * @return true if prime, false otherwise
  6.   */
  7. def isPrime(n: Int): Boolean = {
  8. if (n <= 1) false // 0 and 1 are not primes
  9. else if (n == 2) true // 2 is the only even prime
  10. else if (n % 2 == 0) false // Eliminate even numbers
  11. else {
  12. // Check divisors up to sqrt(n), skipping even numbers
  13. val maxDivisor = math.sqrt(n).toInt
  14. (3 to maxDivisor by 2).forall(n % _ != 0)
  15. }
  16. }
  17.  
  18. /**
  19.   * Generates prime numbers up to a limit using Sieve of Eratosthenes
  20.   * @param limit Upper bound for prime generation
  21.   * @return Sequence of primes up to limit
  22.   */
  23. def sieveOfEratosthenes(limit: Int): Seq[Int] = {
  24. if (limit < 2) Seq.empty
  25. else {
  26. val sieve = Array.fill(limit + 1)(true)
  27. sieve(0) = false
  28. sieve(1) = false
  29.  
  30. for {
  31. i <- 2 to math.sqrt(limit).toInt
  32. if sieve(i)
  33. j <- i * i to limit by i
  34. } sieve(j) = false
  35.  
  36. sieve.zipWithIndex.collect { case (true, num) => num }
  37. }
  38. }
  39.  
  40. def main(args: Array[String]): Unit = {
  41. // Test individual numbers
  42. val testNumbers = List(2, 3, 17, 25, 997, 1000)
  43. println("Prime checks:")
  44. testNumbers.foreach { n =>
  45. println(f"$n%4d is prime: ${isPrime(n)}%5s")
  46. }
  47.  
  48. // Generate primes up to 100
  49. val primesUpTo100 = sieveOfEratosthenes(100)
  50. println("\nPrimes up to 100:")
  51. println(primesUpTo100.mkString(", "))
  52. }
  53. }
Success #stdin #stdout 0.67s 73564KB
stdin
Standard input is empty
stdout
Prime checks:
   2 is prime:  true
   3 is prime:  true
  17 is prime:  true
  25 is prime: false
 997 is prime:  true
1000 is prime: false

Primes up to 100:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97