Given an array arr[] of size N, and integers L and R, the task is to count the number of pairs [arri , arrj] such that i < j and the product of arr[i] * arr[j] lies in the given range [L, R], i.e. L ? arr[i] * arr[j] ? R.
Examples:
Input: arr[ ] = {4, 1, 2, 5}, L = 4, R = 9
Output: 3
Explanation: Valid pairs are {4, 1}, {1, 5} and {4, 2}.Input: arr[ ] = {1, 2, 5, 10, 5}, L = 2, R = 15 Â Â
Output: 6
Explanation: Valid pairs are {1, 2}, {1, 5}, {1, 10}, {1, 5}, {2, 5}, {2, 5}.
Naive Approach: The simplest approach to solve the problem is to generate all possible pairs from the array and for each pair, check if its product lies in the range [L, R] or not.
C++
#include <bits/stdc++.h>using namespace std;Â
// Function to Count pairs from a given array// whose product lies in a given rangeint countPairs(int arr[], int L, int R, int N){    // Variable to store the count    int count = 0;         // Iterating through the array and    // counting all pairs whose product    // is in the range    for (int i = 0; i < N; i++) {        for (int j = i + 1; j < N; j++) {            // Condition            if (arr[i]*arr[j] >= L && arr[i]*arr[j] <= R) {                count++;            }        }    }    // Print the count    cout<<count<<endl;}Â
// Driver Codeint main(){    // Given Input    int arr[] = { 4, 1, 2, 5 };    int l = 4, r = 9;      int n = sizeof(arr) / sizeof(arr[0]);      // Function Call    countPairs(arr, l, r, n);Â
    return 0;}// This code is contributed Pushpesh Raj |
Java
// Java code for above approachimport java.io.*;Â
class GFG {Â
// Function to Count pairs from a given array// whose product lies in a given rangestatic void countPairs(int arr[], int L, int R, int N){    // Variable to store the count    int count = 0;         // Iterating through the array and    // counting all pairs whose product    // is in the range    for (int i = 0; i < N; i++) {        for (int j = i + 1; j < N; j++) {            // Condition            if (arr[i]*arr[j] >= L && arr[i]*arr[j] <= R) {                count++;            }        }    }    // Print the count    System.out.println(count);}Â
// Driver Codepublic static void main (String[] args){    // Given Input    int arr[] = { 4, 1, 2, 5 };    int l = 4, r = 9;Â
    int n = arr.length;Â
    // Function Call    countPairs(arr, l, r, n);Â
}Â
}// This code is contributed Utkarsh Kumar. |
Python3
# Python codeÂ
# Function to Count pairs from a given array# whose product lies in a given rangedef countPairs(arr, L, R, N):     # Variable to store the count    count = 0         # Iterating through the array and    # counting all pairs whose product    # is in the range    for i in range(N):         for j in range(i + 1, N):             # Condition            if (arr[i]*arr[j] >= L and arr[i]*arr[j] <= R):                 count += 1       # Print the count    print(count)   # Driver Codeif __name__ == "__main__":     # Given Input    arr = [ 4, 1, 2, 5 ]    l = 4    r = 9      N = len(arr)       # Function Call    countPairs(arr, l, r, N) |
C#
using System;Â
class GFG {    // Function to Count pairs from a given array whose    // product lies in a given range    static void countPairs(int[] arr, int L, int R, int N) {        // Variable to store the count        int count = 0;                 // Iterating through the array and counting all pairs        // whose product is in the range        for (int i = 0; i < N; i++) {            for (int j = i + 1; j < N; j++) {                // Condition                if (arr[i] * arr[j] >= L && arr[i] * arr[j] <= R) {                    count++;                }            }        }        // Print the count        Console.WriteLine(count);    }Â
    public static void Main() {        // Given Input        int[] arr = { 4, 1, 2, 5 };        int l = 4;          int r = 9;               int n = arr.Length;Â
        // Function Call        countPairs(arr, l, r, n);    }} |
Javascript
// Function to Count pairs from a given array// whose product lies in a given rangefunction countPairs(arr, L, R, N) {// Variable to store the countlet count = 0;// Iterating through the array and// counting all pairs whose product// is in the rangefor (let i = 0; i < N; i++) {     for (let j = i + 1; j < N; j++) {         // Condition        if (arr[i]*arr[j] >= L && arr[i]*arr[j] <= R) {             count += 1;        }    }}Â
// Print the countconsole.log(count);}Â
// Driver Codeif (true) {// Given Inputlet arr = [ 4, 1, 2, 5 ];let l = 4;let r = 9;let N = arr.length;Â
// Function CallcountPairs(arr, l, r, N);} |
3
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: This problem can be solved by Sorting and Binary Search technique. Follow the steps below to solve this problem:
- Sort the array arr[].
- Initialize a variable, say ans as 0, to store the number of pairs whose product lies in the range [L, R].
- Iterate over the range [0, N-1] using a variable i and perform the following steps:
- Find upper bound of an element such that the element is less than equal to R / arr[i].
- Find lower bound of an element such that the element is greater than or equal to L / arr[i].
- Add upper bound – lower bound to ans
- After completing the above steps, print ans.
Below is the implementation of the above approach.
C++
#include<bits/stdc++.h>using namespace std;Â
// Function to count pairs from an array whose product lies in the range [l, r]int countPairs(vector<int> arr, int l, int r, int n) {Â Â Â Â // Sort the array arr[]Â Â Â Â sort(arr.begin(), arr.end());Â
    // Stores the final answer    int ans = 0;Â
    for (int i = 0; i < n; i++) {        // Upper Bound for arr[j] such that arr[j] <= r/arr[i]        auto itr1 = upper_bound(arr.begin(), arr.end(), r / arr[i]);Â
        // Lower Bound for arr[j] such that arr[j] >= l/arr[i]        auto itr2 = lower_bound(arr.begin(), arr.end(), (l + arr[i] - 1) / arr[i]);Â
        ans += max(0, (int)(itr1 - itr2) - (arr[i] * arr[i] >= l && arr[i] * arr[i] <= r));    }Â
    // Return the answer    return ans / 2;}Â
// Driver Codeint main() {    // Given Input    vector<int> arr = {4, 1, 2, 5};    int l = 4;    int r = 9;Â
    int n = arr.size();Â
    // Function Call    cout << countPairs(arr, l, r, n) << endl;Â
    return 0;} |
Java
// Java program for above approachimport java.util.Arrays;Â
class GFG{Â Â Â Â Â // Function to count pairs from an array// whose product lies in the range [l, r]public static void countPairs(int[] arr, int l, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int r, int n){Â Â Â Â Â Â Â Â Â // Sort the array arr[]Â Â Â Â Arrays.sort(arr);Â
    // Stores the final answer    int ans = 0;Â
    for(int i = 0; i < n; i++)     {                 // Upper Bound for arr[j] such        // that arr[j] <= r/arr[i]        int itr1 = upper_bound(arr, 0, arr.length - 1,                                l / arr[i]);Â
        // Lower Bound for arr[j] such        // that arr[j] >= l/arr[i]        int itr2 = lower_bound(arr, 0, arr.length - 1,                                l / arr[i]);        ans += itr1 - itr2;    }Â
    // Print the answer    System.out.println(ans);}Â
public static int lower_bound(int[] arr, int low,                              int high, int X){         // Base Case    if (low > high)     {        return low;    }Â
    // Find the middle index    int mid = 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);}Â
public static int upper_bound(int[] arr, int low,                               int high, int X) {         // Base Case    if (low > high)        return low;Â
    // Find the middle index    int mid = 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 Codepublic static void main(String args[]){         // Given Input    int[] arr = { 4, 1, 2, 5 };    int l = 4, r = 9;    int n = arr.length;Â
    // Function Call    countPairs(arr, l, r, n);}}Â
// This code is contributed by gfgking. |
Python3
# Python program for above approachÂ
# Function to count pairs from an array# whose product lies in the range [l, r]def countPairs(arr, l, r, n):Â
    # Sort the array arr[]    arr[::-1]Â
    # Stores the final answer    ans = 0;Â
    for i in range(n):Â
        # Upper Bound for arr[j] such        # that arr[j] <= r/arr[i]        itr1 = upper_bound(arr, 0, len(arr) - 1, l // arr[i])Â
        # Lower Bound for arr[j] such        # that arr[j] >= l/arr[i]        itr2 = lower_bound(arr, 0, len(arr) - 1, l // arr[i]);Â
        ans += itr1 - itr2;Â
    # Print the answer    print(ans);Â
def lower_bound(arr, low, high, X):Â
    # Base Case    if (low > high):        return low;Â
    # Find the middle index    mid = 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);Â
def upper_bound(arr, low, high, X):Â
    # Base Case    if (low > high):        return low;Â
    # Find the middle index    mid = 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 Inputarr = [4, 1, 2, 5];l = 4;r = 9;Â
n = len(arr)Â
# Function CallcountPairs(arr, l, r, n);Â
# This code is contributed by _Saurabh_Jaiswal. |
C#
// C# program for the above approachusing System;Â
class GFG{Â
// Function to count pairs from an array// whose product lies in the range [l, r]public static void countPairs(int[] arr, int l,                              int r, int n){         // Sort the array arr[]    Array.Sort(arr);      // Stores the final answer    int ans = 0;      for(int i = 0; i < n; i++)    {                 // Upper Bound for arr[j] such        // that arr[j] <= r/arr[i]        int itr1 = upper_bound(arr, 0, arr.Length - 1,                               l / arr[i]);          // Lower Bound for arr[j] such        // that arr[j] >= l/arr[i]        int itr2 = lower_bound(arr, 0, arr.Length - 1,                               l / arr[i]);        ans += itr1 - itr2;    }      // Print the answer    Console.WriteLine(ans);}  public static int lower_bound(int[] arr, int low,                              int high, int X){         // Base Case    if (low > high)    {        return low;    }      // Find the middle index    int mid = 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);}  public static int upper_bound(int[] arr, int low,                              int high, int X){         // Base Case    if (low > high)        return low;      // Find the middle index    int mid = 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 codepublic static void Main(string[] args){         // Given Input    int[] arr = { 4, 1, 2, 5 };    int l = 4, r = 9;    int n = arr.Length;         // Function Call    countPairs(arr, l, r, n);}}Â
// This code is contributed by sanjoy_62 |
Javascript
<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 Inputlet arr = [4, 1, 2, 5];let l = 4, r = 9;Â
let n = arr.lengthÂ
// Function CallcountPairs(arr, l, r, n);Â
// This code is contributed by gfgking.</script> |
3
Â
Time Complexity: O(NlogN)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
