Find x and y dividing a and b with specific conditions, choosing the smallest pair; output x and y or -1 if no valid pair exists.

by Bhavik Bamania

HTML

2. You are given two integers a and b.
Find two integers x and y such that:

1. x divides a.
2. y divides b.
3. x + y divides both a and b.
4. x > 1 and y > 1

If there are multiple valid pairs (x, y), choose the one with the smallest x.
If there are still multiple options, choose the one with the smallest y.
If no such pair exists, print -1.

Input
Two integers a and b 
Output
Print two integers x and y — the required pair.
If no valid pair exists, print -1.

Example 1
Input
12 18

Output
3 3

Explanation
• Divisors of 12 are [1, 2, 3, 4, 6, 12].
• Divisors of 18 are [1, 2, 3, 6, 9, 18].
• Pair (3, 3) works because 3 | 12, 3 | 18, and (3 + 3) = 6 divides both 12 and 18.
• This is the lexicographically smallest valid pair.

Example 2
Input
7 11

Output
-1

Explanation
No divisors x of 7 and y of 11 satisfy the condition that x + y divides both 7 and 11.

Constraints :
2 ≤ a, b ≤ 10^6

Time complexity : O(√a + √b + d(a) * d(b))
Space Complexity : O(d(a) + d(b))
d(x) : number of divisors of x