How to find A and B where A and B are prime numbers and A * B = 12349 in Scala

1 Answer

0 votes
import scala.math.sqrt

object FindABProgram {

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

    val limit: Int = sqrt(n.toDouble).toInt
    var i: Int = 5

    while (i <= limit) {
      if (n % i == 0 || n % (i + 2) == 0)
        return false
      i += 6
    }

    true
  }

  // Helper class to return A and B together
  case class Pair(A: Int, B: Int)

  // Function to find the two prime factors A and B
  def findAB(N: Int): Pair = {
    val limit: Int = sqrt(N.toDouble).toInt
    var result: Pair = Pair(-1, -1) // default: No prime factors found

    var i: Int = 2
    while (i <= limit && result.A == -1) {
      if (N % i == 0) {
        val j: Int = N / i
        if (isPrime(i) && isPrime(j)) {
          result = Pair(i, j)
        }
      }
      i += 1
    }

    result
  }

  def main(args: Array[String]): Unit = {
    val N: Int = 12349

    val result: Pair = findAB(N)

    if (result.A != -1)
      println(s"A = ${result.A}, B = ${result.B}")
    else
      println("Not found.")
  }
}



/*
run:

A = 53, B = 233

*/

 



answered 10 hours ago by avibootz

Related questions

...