<script>
// Javascript program for above approach
// Function to count pairs from an array
// whose product lies in the range [l, r]
function countPairs(arr, l, r, n)
{
// Sort the array arr[]
arr.sort((a, b) => a - b);
// Stores the final answer
let ans = 0;
for (let i = 0; i < n; i++)
{
// Upper Bound for arr[j] such
// that arr[j] <= r/arr[i]
let itr1 = upper_bound(arr, 0, arr.length - 1, Math.floor(l / arr[i]));
// Lower Bound for arr[j] such
// that arr[j] >= l/arr[i]
let itr2 = lower_bound(arr, 0, arr.length - 1, Math.floor(l / arr[i]));
ans += itr1 - itr2;
}
// Print the answer
document.write(ans + "<br>");
}
function lower_bound(arr, low, high, X) {
// Base Case
if (low > high) {
return low;
}
// Find the middle index
let mid = Math.floor(low + (high - low) / 2);
// If arr[mid] is greater than
// or equal to X then search
// in left subarray
if (arr[mid] >= X) {
return lower_bound(arr, low, mid - 1, X);
}
// If arr[mid] is less than X
// then search in right subarray
return lower_bound(arr, mid + 1, high, X);
}
function upper_bound(arr, low, high, X) {
// Base Case
if (low > high)
return low;
// Find the middle index
let mid = Math.floor(low + (high - low) / 2);
// If arr[mid] is less than
// or equal to X search in
// right subarray
if (arr[mid] <= X) {
return upper_bound(arr, mid + 1, high, X);
}
// If arr[mid] is greater than X
// then search in left subarray
return upper_bound(arr, low, mid - 1, X);
}
// Driver Code
// Given Input
let arr = [4, 1, 2, 5];
let l = 4, r = 9;
let n = arr.length
// Function Call
countPairs(arr, l, r, n);
// This code is contributed by gfgking.
</script>