Firstly....to answer why your approach
simply finding the prime factors of n and searching for the combination where a,b are factors of n and a - b is minimized
is not optimal:
Suppose your number is n = 2^7 * 3^4 * 5^2 * 7 * 11 * 13 (=259459200)
, well within range of int
. From the combinatorics theory, this number has exactly (8 * 5 * 3 * 2 * 2 * 2 = 960)
factors. So, firstly you find all of these 960 factors, then find all pairs (a,b) such that a * b = n
, which in this case will be (6C1 + 9C2 + 11C3 + 13C4 + 14C5 + 15C6 + 16C7 + 16C8)
ways. (if I'm not wrong, my combinatorics is a bit weak). This is of the order 1e5
if implemented optimally. Also, implementation of this approach is hard.
Now, why the difference of squares approach
represent S - n = Q, such that S and Q are perfect squares
is good:
This is because if you can represent S - n = Q
, this implies, n = S - Q
=> n = s^2 - q^2
=> n = (s+q)(s-q)
=> Your reqd ans = 2 * q
Now, even if you iterate for all squares, you will either find your answer or terminate when difference of 2 consecutive squares is greater than n
But I don't think this will be doable for all n
(eg. if n=6
, there is no solution for (S,Q)
.)
Another approach:
Iterate from floor(sqrt(n))
to 1. The first number (say, x), such that x|n
will be one of the numbers in the required pair (a,b)
. Other will be, obvs, y = x/n
. So, your answer will be y - x
.
This is O(sqrt(n))
time complex algorithm.