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

1 Answer

0 votes
import java.lang.Math;

public class FindABProgram {

    // Function to check if a number is prime
    static boolean isPrime(int n) {
        if (n <= 1) return false;
        if (n <= 3) return true;
        if (n % 2 == 0 || n % 3 == 0) return false;

        int limit = (int)Math.sqrt(n);
        for (int i = 5; i <= limit; i += 6) {
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
        }

        return true;
    }

    // Helper class to return A and B together
    static class Pair {
        int A, B;
        Pair(int A, int B) { this.A = A; this.B = B; }
    }

    // Function to find the two prime factors A and B
    static Pair findAB(int N) {
        int limit = (int)Math.sqrt(N);

        for (int i = 2; i <= limit; i++) {
            if (N % i == 0) {
                int j = N / i;
                if (isPrime(i) && isPrime(j)) {
                    return new Pair(i, j);
                }
            }
        }

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

    public static void main(String[] args) {
        int N = 12349;

        Pair result = findAB(N);

        if (result.A != -1)
            System.out.println("A = " + result.A + ", B = " + result.B);
        else
            System.out.println("Not found.");
    }
}


/*
run:

A = 53, B = 233

*/

 



answered Jun 5 by avibootz

Related questions

...