'Given an array find all the pairs with product between a given range

Given an array having n elements, find all the possible pairs of elements whose product is between x and y provided by the user, i.e. all i and j less than n, s.t. x <= a[i] * a[j] <= y.

A naive approach is to use two nested loops and check if the product lies in the given range increase the count. The time complexity of this approach will be n^2.

How can we do better?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source