I wanted to Calculate num of Pairs of (m,n) where GCD(m,n)=x, say x=1 and 1<=m<=M=10^5 and 1<=n<=N=10^5.
M and N will be given
Note: I just want the number of possible pairs and not the pairs.
TIME LIMIT : 5 Secs
The below code works good for small numbers, but for larger ones it gives me StackOverflowError
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class TestClass{
static long M;
static long N;
static long totalCount = 1;
public static void main(String[] args) throws Exception{
M = 100000;
N = 2000;
findCoPrimes(2, 1);
findCoPrimes(3, 1);
System.out.println(totalCount);
}
public static void findCoPrimes(int m, int n){
if ((n > N) || (m > M)){
return;
}
if (n != m && m <= N){
totalCount++;
}
totalCount++;
findCoPrimes(2*m - n, m);
findCoPrimes(2*m + n, m);
findCoPrimes(m + 2*n, n);
}
}
Can someone help me convert this recursive function to an iterative function to avoid the StackOverflow error.
Please help me find a solution for this. Any other better approaches will also be considered. There is a hint with this question - Use smart ways to find the prime factors and then find the number of co prime pairs. Brute force wont work.