Amazon | OA | Count pairs whose sum divides product

This problem was asked recently in Online Assessment of a product based company,
even though the brute force code got accepted, is there any efficient method to solve this ?

Problem:
You are given a N. Find the number of pairs (a, b) within the given range N such that the sum of the two numbers divides the product of the two numbers.

Constraints:
1 <= a, b <= N
a != b
1 <= N <= 10^5
1 <= T <= 10 (Test cases)

Input & Output Format:
1st line contains an integer T (number of testcases), 1st and only line of each testcase contains an integer N
Print number of such pairs (a, b) on a new line for each testcase

Sample Input:
2
2
15

Sample Output:
0
4

Explanation:
For second testcase the requied pairs are (3, 6), (4, 12), (6, 12) and (10, 15)

Brute force C++ code:

int main() {
    int t; cin >> t;
    while(t--) {
        int n; cin >> n;
        int ans = 0;
        for(int i = 3; i < n; i++) {
            for(int j = i + 1; j <= n; j++) {
                if((i * j) % (i + j) == 0)
                    ans++;
            }
        }
        cout << ans << endl;
    }
}

Time complexity of the above code is O(N^2).
I'm not able to think of any better approach than brute force.
Can anyone help to solve this problem with better time complexity or any mathematical observation / pattern that you can think of ?

Thanks in advance :)


Comments (4)