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

1 Answer

0 votes
import Foundation

// Function to check if a number is prime
func isPrime(_ n: Int) -> Bool {
    if n <= 1 { return false }
    if n <= 3 { return true }
    if n % 2 == 0 || n % 3 == 0 { return false }

    let limit: Int = Int(sqrt(Double(n)))
    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
struct Pair {
    var A: Int
    var B: Int
}

// Function to find the two prime factors A and B
func findAB(_ N: Int) -> Pair {
    let limit: Int = Int(sqrt(Double(N)))

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

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

func main() {
    let N: Int = 12349

    let result: Pair = findAB(N)

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

main()



/*
run:

A = 53, B = 233

*/

 



answered 9 hours ago by avibootz

Related questions

...