How to find the first 4-digit prime number where all digits are unique in Scala

1 Answer

0 votes
object UniquePrimeFinder {

  // Function to check if a number is prime
  def isPrime(n: Int): Boolean = {
    if (n < 2) return false
    if (n % 2 == 0) return n == 2

    val limit = math.sqrt(n).toInt
    
    (3 to limit by 2).forall(n % _ != 0)
  }

  // Function to check if all digits are unique
  def hasUniqueDigits(n: Int): Boolean = {
    val digits = n.toString
    
    digits.toSet.size == digits.length
  }

  def main(args: Array[String]): Unit = {
    val result = (1000 to 9999).find(num => isPrime(num) && hasUniqueDigits(num))

    result match {
      case Some(num) => println(s"First 4-digit prime with all unique digits: $num")
      case None      => println("No such number found.")
    }
  }
}




/*
run:

First 4-digit prime with all unique digits: 1039

*/

 



answered 9 hours ago by avibootz
...