Open In App

Count of pairs in given Array with product of their values equal to sum of their indices (arr[i]*arr[j] = i+j)

Last Updated : 09 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of length N with distinct integers from 1 to 2*N, the task is to count the number of pairs of indices (i, j) such that (i < j) and arr[i] * arr[j] = i + j, i.e. calculate the number of pairs such that their product is equal to their sum of indices.

Examples: 

Input: N = 5, arr[] = {3, 1, 5, 9, 2}
Output: 3
Explanation: There are three pairs (i, j) such that (i < j) and arr[i] * arr[j] = i + j (1, 2), (1, 5), (2, 3)

Input: N = 3, arr[] = {6, 1, 5}
Output: 1

 

Naive Approach: Iterate over all pairs of indices (i, j) with (i < j) and check for each pair if the above condition is satisfied, then increase the answer by 1 otherwise go to the next pair.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the number of
// unique pairs
int NumberOfRequiredPairs(int arr[], int N)
{
 
    // Variable that with stores number
    // of valid pairs
    int ans = 0;
 
    // Traverse the array for every
    // possible index i
    for (int i = 0; i < N; i++)
 
        // Traverse the array for every
        // possible j (i < j)
        // Please note that the indices
        // are used as 1 based indexing
        for (int j = i + 1; j < N; j++)
            if ((arr[i] * arr[j])
                == ((i + 1) + (j + 1)))
                ans++;
 
    // Return the ans
    return ans;
}
 
// Driver Code
int main()
{
    // Given Input
    int N = 5;
    int arr[] = { 3, 1, 5, 9, 2 };
 
    // Function Call
    cout << NumberOfRequiredPairs(arr, N);
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
class GFG
{
 
// Function to find the number of
// unique pairs
static int NumberOfRequiredPairs(int arr[], int N)
{
 
    // Variable that with stores number
    // of valid pairs
    int ans = 0;
 
    // Traverse the array for every
    // possible index i
    for (int i = 0; i < N; i++)
 
        // Traverse the array for every
        // possible j (i < j)
        // Please note that the indices
        // are used as 1 based indexing
        for (int j = i + 1; j < N; j++)
            if ((arr[i] * arr[j])
                == ((i + 1) + (j + 1)))
                ans++;
 
    // Return the ans
    return ans;
}
 
// Driver code
public static void main (String[] args)
{
   
    // Given Input
    int N = 5;
    int arr[] = { 3, 1, 5, 9, 2 };
 
    // Function Call
    System.out.println(NumberOfRequiredPairs(arr, N));
}
}
 
// This code is contributed by sanjoy_62.


Python3




# Python program for the above approach
 
# Function to find the number of
# unique pairs
def NumberOfRequiredPairs(arr, N):
 
    # Variable that with stores number
    # of valid pairs
    ans = 0
 
    # Traverse the array for every
    # possible index i
    for i in range(N):
 
        # Traverse the array for every
        # possible j (i < j)
        # Please note that the indices
        # are used as 1 based indexing
        for j in range(i + 1, N):
            if ((arr[i] * arr[j]) == ((i + 1) + (j + 1))):
                ans += 1
 
    # Return the ans
    return ans
 
# Driver Code
# Given Input
N = 5
arr = [3, 1, 5, 9, 2]
 
# Function Call
print(NumberOfRequiredPairs(arr, N))
 
# This code is contributed by Saurabh Jaiswal


C#




// C# program for the above approach
using System;
class GFG
{
 
// Function to find the number of
// unique pairs
static int NumberOfRequiredPairs(int []arr, int N)
{
 
    // Variable that with stores number
    // of valid pairs
    int ans = 0;
 
    // Traverse the array for every
    // possible index i
    for (int i = 0; i < N; i++)
 
        // Traverse the array for every
        // possible j (i < j)
        // Please note that the indices
        // are used as 1 based indexing
        for (int j = i + 1; j < N; j++)
            if ((arr[i] * arr[j])
                == ((i + 1) + (j + 1)))
                ans++;
 
    // Return the ans
    return ans;
}
 
// Driver code
public static void  Main ()
{
   
    // Given Input
    int N = 5;
    int []arr = { 3, 1, 5, 9, 2 };
 
    // Function Call
    Console.Write(NumberOfRequiredPairs(arr, N));
}
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
// Javascript program for the above approach
 
// Function to find the number of
// unique pairs
function NumberOfRequiredPairs(arr, N)
{
 
    // Variable that with stores number
    // of valid pairs
    let ans = 0;
 
    // Traverse the array for every
    // possible index i
    for (let i = 0; i < N; i++)
 
        // Traverse the array for every
        // possible j (i < j)
        // Please note that the indices
        // are used as 1 based indexing
        for (let j = i + 1; j < N; j++)
            if ((arr[i] * arr[j])
                == ((i + 1) + (j + 1)))
                ans++;
 
    // Return the ans
    return ans;
}
 
// Driver Code
// Given Input
let N = 5;
let arr = [ 3, 1, 5, 9, 2 ];
 
// Function Call
document.write(NumberOfRequiredPairs(arr, N));
 
// This code is contributed by Samim Hossain Mondal.
</script>


Output

3

Time Complexity: O(N^2)
Auxiliary Space: O(1)

Efficient Approach : Rewrite the mentioned condition as 
 

arr[j] = (i + j)/arr[i]

 
Therefore, for each multiple of arr[i], find the respective j and check whether arr[j] is equal to (i + j)/ arr[i]. This approach is efficient because for each i it is required to go through each multiple of i till 2*N. As all numbers in the array are distinct, it can be concluded that the total iterations for calculating j will be like: 

N + N/2 + N/3 + N/4 + N/5…… 

This is a well-known result of the series of expansions of logN. For more information read about this here. Follow the steps below to solve the problem:

 

  • Initialize the variable ans as 0 to store the answer.
  • Iterate over the range [0, N] using the variable i and perform the following steps:
    • Initialize the variable k as the value of arr[i].
    • Iterate in a while loop till k is less than equal to 2*N and perform the following tasks:
      • Initialize the variable j as k-i-1.
      • If j is greater than equal to 1 and less than equal to N and arr[j – 1] is equal to k / arr[i] and j is greater than i+1, then increase the value of ans by 1.
  • After performing the above steps, print the value of ans as the answer.

 

Below is the implementation of the above approach: 

 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the number of
// unique pairs
int NumberOfRequiredPairs(int arr[], int N)
{
 
    // Variable that with stores
    // number of valid pairs
    int ans = 0;
 
    // Traverse the array for every
    // possible index i
    for (int i = 0; i < N; i++) {
 
        // Initialize a dummy variable
        // for arr[i]
        int k = arr[i];
 
        // We will loop through every
        // multiple of arr[i];
        // Looping through 2*N because
        // the maximum element
        // in array can be 2*N
        // Please not that i and j are
        // in 1 based indexing
        while (k <= 2 * N) {
 
            // Calculating j
            int j = k - i - 1;
 
            // Now check if this j lies
            // between the bounds
            // of the array
            if (j >= 1 && j <= N) {
 
                // Checking the required
                // condition
                if ((arr[j - 1] == k / arr[i])
                    && j > i + 1) {
                    ans++;
                }
            }
 
            // Increasing k to its next multiple
            k += arr[i];
        }
    }
 
    // Return the ans
    return ans;
}
 
// Driver Code
int main()
{
    // Given Input
    int N = 5;
    int arr[] = { 3, 1, 5, 9, 2 };
 
    // Function Call
    cout << NumberOfRequiredPairs(arr, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
public class GFG
{
 
// Function to find the number of
// unique pairs
static int NumberOfRequiredPairs(int arr[], int N)
{
 
    // Variable that with stores
    // number of valid pairs
    int ans = 0;
 
    // Traverse the array for every
    // possible index i
    for (int i = 0; i < N; i++) {
 
        // Initialize a dummy variable
        // for arr[i]
        int k = arr[i];
 
        // We will loop through every
        // multiple of arr[i];
        // Looping through 2*N because
        // the maximum element
        // in array can be 2*N
        // Please not that i and j are
        // in 1 based indexing
        while (k <= 2 * N) {
 
            // Calculating j
            int j = k - i - 1;
 
            // Now check if this j lies
            // between the bounds
            // of the array
            if (j >= 1 && j <= N) {
 
                // Checking the required
                // condition
                if ((arr[j - 1] == k / arr[i])
                    && j > i + 1) {
                    ans++;
                }
            }
 
            // Increasing k to its next multiple
            k += arr[i];
        }
    }
 
    // Return the ans
    return ans;
}
 
// Driver code
public static void main (String args[])
{
   
    // Given Input
    int N = 5;
    int arr[] = { 3, 1, 5, 9, 2 };
 
    // Function Call
    System.out.println(NumberOfRequiredPairs(arr, N));
}
}
 
// This code is contributed by Samim Hossain Mondal.


Python3




# Python3 program for the above approach
 
# Function to find the number of
# unique pairs
def NumberOfRequiredPairs(arr, N) :
 
    # Variable that with stores
    # number of valid pairs
    ans = 0;
 
    # Traverse the array for every
    # possible index i
    for i in range(N) :
 
        # Initialize a dummy variable
        # for arr[i]
        k = arr[i];
 
        # We will loop through every
        # multiple of arr[i];
        # Looping through 2*N because
        # the maximum element
        # in array can be 2*N
        # Please not that i and j are
        # in 1 based indexing
        while (k <= 2 * N) :
 
            # Calculating j
            j = k - i - 1;
 
            # Now check if this j lies
            # between the bounds
            # of the array
            if (j >= 1 and j <= N) :
 
                # Checking the required
                # condition
                if ((arr[j - 1] == k // arr[i]) and j > i + 1) :
                    ans += 1;
 
            # Increasing k to its next multiple
            k += arr[i];
 
    # Return the ans
    return ans;
 
# Driver Code
if __name__ == "__main__" :
 
    # Given Input
    N = 5;
    arr = [ 3, 1, 5, 9, 2 ];
 
    # Function Call
    print(NumberOfRequiredPairs(arr, N));
 
    # This code is contributed by AnkThon


C#




// C# program for the above approach
using System;
class GFG
{
 
// Function to find the number of
// unique pairs
static int NumberOfRequiredPairs(int []arr, int N)
{
 
    // Variable that with stores
    // number of valid pairs
    int ans = 0;
 
    // Traverse the array for every
    // possible index i
    for (int i = 0; i < N; i++) {
 
        // Initialize a dummy variable
        // for arr[i]
        int k = arr[i];
 
        // We will loop through every
        // multiple of arr[i];
        // Looping through 2*N because
        // the maximum element
        // in array can be 2*N
        // Please not that i and j are
        // in 1 based indexing
        while (k <= 2 * N) {
 
            // Calculating j
            int j = k - i - 1;
 
            // Now check if this j lies
            // between the bounds
            // of the array
            if (j >= 1 && j <= N) {
 
                // Checking the required
                // condition
                if ((arr[j - 1] == k / arr[i])
                    && j > i + 1) {
                    ans++;
                }
            }
 
            // Increasing k to its next multiple
            k += arr[i];
        }
    }
 
    // Return the ans
    return ans;
}
 
// Driver code
public static void  Main ()
{
   
    // Given Input
    int N = 5;
    int []arr = { 3, 1, 5, 9, 2 };
 
    // Function Call
    Console.Write(NumberOfRequiredPairs(arr, N));
}
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
// Javascript program for the above approach
 
// Function to find the number of
// unique pairs
function NumberOfRequiredPairs(arr, N)
{
 
    // Variable that with stores
    // number of valid pairs
    let ans = 0;
 
    // Traverse the array for every
    // possible index i
    for (let i = 0; i < N; i++) {
 
        // Initialize a dummy variable
        // for arr[i]
        let k = arr[i];
 
        // We will loop through every
        // multiple of arr[i];
        // Looping through 2*N because
        // the maximum element
        // in array can be 2*N
        // Please not that i and j are
        // in 1 based indexing
        while (k <= 2 * N) {
 
            // Calculating j
            let j = k - i - 1;
 
            // Now check if this j lies
            // between the bounds
            // of the array
            if (j >= 1 && j <= N) {
 
                // Checking the required
                // condition
                if ((arr[j - 1] == k / arr[i])
                    && j > i + 1) {
                    ans++;
                }
            }
 
            // Increasing k to its next multiple
            k += arr[i];
        }
    }
 
    // Return the ans
    return ans;
}
 
// Driver Code
// Given Input
let N = 5;
let arr = [ 3, 1, 5, 9, 2 ];
 
// Function Call
document.write(NumberOfRequiredPairs(arr, N));
 
// This code is contributed by Samim Hossain Mondal.
</script>


Output

3

Time Complexity: O(N*log(N))
Auxiliary Space: O(1)



Similar Reads

Count pairs (i, j) from an array such that |arr[i]| and |arr[j]| both lies between |arr[i] - arr[j]| and |arr[i] + arr[j]|
Given an array arr[] of size N, the task is to count the number of pairs (arr[i], arr[j]) such that |arr[i]| and |arr[j]| lies between |arr[i] - arr[j]| and |arr[i] + arr[j]|. Examples: Input: arr[] = {1, 3, 5, 7} Output: 2 Explanation: Pair (arr[1], arr[2]) (= (3, 5)) lies between |3 - 5| (= 2) and |3 + 5| (= 8).Pair (arr[2], arr[3]) (= (5, 7)) li
6 min read
Check whether (i,j) exists such that arr[i] != arr[j] and arr[arr[i]] is equal to arr[arr[j]]
Given an array A[]. The task is to determine if it is possible to choose two indices 'i' and 'j' such that the below conditions gets satisfied:- A[i] is not equal to A[j].A[A[i]] is equal to A[A[j]]. Note: The value of the elements in an array is less than the value of N i.e. For every i, arr[i] &lt; N. Examples: Input: N = 4, A[] = {1, 1, 2, 3} Ou
10 min read
Maximum value of |arr[0] - arr[1]| + |arr[1] - arr[2]| + ... +|arr[n - 2] - arr[n - 1]| when elements are from 1 to n
Given an array arr[] of size n whose elements are from the range [1, n]. The task is to find maximum value of |arr[0] - arr[1]| + |arr[1] - arr[2]| + ... +|arr[n - 2] - arr[n - 1]|. You can arrange the numbers in the array in any order. Examples: Input: arr[] = {1, 2, 3, 4} Output: 7 Arrange the array in this way for max value, arr[] = {3, 1, 4, 2}
3 min read
Minimize last remaining element of Array by selecting pairs such that arr[i] &gt;= arr[j] and replace arr[i] with arr[i] - arr[j]
Given an array arr[] of N positive integers, the task is to find the smallest possible value of the last remaining element in the array after performing the following operations any number of times: Select a pair of indices (i, j) such that arr[i] &gt;= arr[j] and replace arr[i] with arr[i] - arr[j].If an array element arr[i] &lt;= 0, remove it fro
5 min read
Count of pairs (arr[i], arr[j]) such that arr[i] + j and arr[j] + i are equal
Given an array arr[], the task is to count pairs i, j such that, i &lt; j and arr[i] + j = arr[j] + i. Examples: Input: arr[] = {4, 1, 2, 3}Output: 3Explanation: In total three pairs are satisfying the given condition those are {1, 2}, {2, 3} and {1, 3}.So, the final answer is 3. Input: arr[] = {1, 5, 6}Output: 1 Naive Approach: The naive approach
5 min read
Count of indices pairs such that product of elements at these indices is equal to absolute difference of indices
Given an array arr[] consisting of N positive integers, the task is to find the number of pairs (i, j) such that i &lt; j and the product of elements at these indices is equal to the absolute difference of their indices. Examples: Input: arr[] = {1, 1, 2, 4}Output: 2Explanation:Following are the possible pairs: (0, 1): The sum of these indices is 0
10 min read
Count pairs in an array such that LCM(arr[i], arr[j]) &gt; min(arr[i],arr[j])
Given an array arr[], the task is to find the count of pairs in the array such that LCM(arr[i], arr[j]) &gt; min(arr[i], arr[j]) Note: Pairs (arr[i], arr[j]) and (arr[j], arr[i]) are considered identical and will be counted only once. Examples: Input: arr[] = {1, 1, 4, 9} Output: 5 All valid pairs are (1, 4), (1, 9), (1, 4), (1, 9) and (4, 9). Inpu
9 min read
Count number of pairs (i, j) such that arr[i] * arr[j] &gt; arr[i] + arr[j]
Given an array arr[] of non-negative integers, the task is to count pairs of indices (i, j such that arr[i] * arr[j] &gt; arr[i] + arr[j] where i &lt; j. Examples: Input: arr[] = { 5, 0, 3, 1, 2 } Output: 3 Input: arr[] = { 1, 1, 1 } Output: 0 Naive Approach: Run two nested loops and check for every pair whether the condition is satisfied. If the c
9 min read
Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]
Given an array arr[] of N integers, the task is to find the count of unordered index pairs (i, j) such that i != j and 0 &lt;=i &lt; j &lt; N and either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]. Examples: Input: arr[] = {2, 4} Output: 1 (0, 1) is the only index pair possible. Input: arr[] = {3, 2, 4, 2, 6} Output: 6 Possible p
7 min read
Count number of pairs (i, j) such that arr[i] * arr[j] = arr[i] + arr[j]
Given an array arr[] of length N, count the number of pairs (i, j) such that arr[i] * arr[j] = arr[i] + arr[j] and 0 &lt;= i &lt; j &lt;= N. It is also given that elements of the array can be any positive integers including zero. Examples: Input : arr[] = {2, 0, 3, 2, 0} Output : 2 Input : arr[] = {1, 2, 3, 4} Output : 0 Simple solution: We can gen
8 min read
Article Tags :
Practice Tags :