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

1 Answer

0 votes
import kotlin.math.sqrt

// Function to check if a number is prime
fun 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
    }

    return true
}

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

// Function to find the two prime factors A and B
fun findAB(N: Int): Pair {
    val limit: Int = sqrt(N.toDouble()).toInt()

    for (i: Int in 2..limit) {
        if (N % i == 0) {
            val j: Int = N / i
            if (isPrime(i) && isPrime(j)) {
                return Pair(i, j)
            }
        }
    }

    return Pair(-1, -1) // No prime factors found
}

fun main() {
    val N: Int = 12349

    val result: Pair = findAB(N)

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



/*
run:

A = 53, B = 233

*/

 



answered 10 hours ago by avibootz

Related questions

...