Count of pair of integers (x , y) such that difference between square of x and y is a perfect square
Given an integer N. The task is to find the number of pairs of integers (x, y) both less than N and greater than 1, such that x2 – y is a square number or 0.
Input: N = 3
The only possible valid pairs are (1, 1), (2, 3). Therefore, the count of such pairs is 2.
Input: N = 2
Naive Approach: The simplest approach to solve the given problem is to generate all possible pairs of integers (x, y) over the range [1, N] and then check that if the value of (x2 – y) is a perfect square or not. If found to be true, then count this pair. After checking for all the possible, print the total count obtained.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by the following observation:
x2-y is a square of a number, let’s say square of z.
x2 – y = z2
x2 – z2 = y
( x + z ) * ( x – z ) = y
Now, let x + z = p and x – z = q
p * q = y
So, the problem gets reduced to count the pairs of p, q instead of x, y.
Now, as y can only be in the range of 1 to N
So, p*q will also be in the range from 1 to N. And as p>=q ( because x+z >= x-z ), q will be in the range from 1 to √N and p will be in the range of 1 to N/q.
Also p+q = 2*x, so x = (p+q)/2.
Now, as x can have a max value of N, therefore
(p+q)/2 <= N
p <= 2*N-q
So, the max value of p = min ( 2*N – q, N/q).
Now, after knowing the ranges of p & q, try all possible values of p & q. And after fixing, all possible pairs possible are (l, q) where l is in the range from q to maximum value of p.
So, the total number of pairs formed are (p – q + 1), say cnt.
Now, as we know that p=x+z and q=x-z, so both p & q are either even or odd. And based on this conclusion, if q is even the total valid pairs are cnt/2 (after removing all pairs with an even value of p) and if it is odd then the total number of valid pairs are (cnt/2 + 1).
Below is the implementation of the above approach:
Time Complexity: O(N1/2)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.