Problem: Given A,B print the number of pairs (a,b) such that GCD(a,b)=1 and 1<=a<=A and 1<=b<=B.
Solution (Brute Force Approach) In the below code, i have used brute force approach and it works fine. However the execution time is more 10 sec if A & B > 10^5
Alternative Solution From my research i found out that finding prime factors of A & B will reduce the execution time considerably (< 3 sec), but i'm not sure how to apply it.
Need Help: Can anyone help me to arrive at the result with < 3 sec execution time?
class GCD {
public static void main(String[] args) {
int A = 0, B = 0, GCD = 0, count = 0;
BigInteger B1, B2 = null;
A = Integer.parseInt(args[0]);
B = Integer.parseInt(args[1]);
for (int a = 1; a <= A; a++) {
for (int b = 1; b <= B; b++) {
B1 = BigInteger.valueOf(a);
B2 = BigInteger.valueOf(b);
GCD = calculateGCD(B1, B2);
if (GCD == 1) {
count++;
}
}
}
System.out.println(count);
}
public static int calculateGCD(BigInteger number1, BigInteger number2) {
return (number1.gcd(number2)).intValue();
}
}