Pair with given product | Set 1 (Find if any pair exists)
Last Updated :
27 Dec, 2023
Given an array of distinct elements and a number x, find if there is a pair with a product equal to x.
Examples :
Input : arr[] = {10, 20, 9, 40};
int x = 400;
Output : Yes
Input : arr[] = {10, 20, 9, 40};
int x = 190;
Output : No
Input : arr[] = {-10, 20, 9, -40};
int x = 400;
Output : Yes
Input : arr[] = {-10, 20, 9, 40};
int x = -400;
Output : Yes
Input : arr[] = {0, 20, 9, 40};
int x = 0;
Output : Yes
Naive approach: Run two loops to consider all possible pairs. For every pair, check if the product is equal to x or not.
C++
#include<bits/stdc++.h>
using namespace std;
bool isProduct( int arr[], int n, int x)
{
for ( int i=0; i<n-1; i++)
for ( int j=i+1; j<n; j++)
if (arr[i] * arr[j] == x)
return true ;
return false ;
}
int main()
{
int arr[] = {10, 20, 9, 40};
int x = 400;
int n = sizeof (arr)/ sizeof (arr[0]);
isProduct(arr, n, x)? cout << "Yes\n"
: cout << "No\n" ;
x = 190;
isProduct(arr, n, x)? cout << "Yes\n"
: cout << "No\n" ;
return 0;
}
|
Java
class GFG
{
boolean isProduct( int arr[], int n, int x)
{
for ( int i= 0 ; i<n- 1 ; i++)
for ( int j=i+ 1 ; j<n; j++)
if (arr[i]*arr[j] == x)
return true ;
return false ;
}
public static void main(String[] args)
{
GFG g = new GFG();
int arr[] = { 10 , 20 , 9 , 40 };
int x = 400 ;
int n = arr.length;
if (g.isProduct(arr, n, x))
System.out.println( "Yes" );
else
System.out.println( "No" );
x = 190 ;
if (g.isProduct(arr, n, x))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isProduct(arr, n, x):
for i in arr:
for j in arr:
if i * j = = x:
return True
return False
arr = [ 10 , 20 , 9 , 40 ]
x = 400
n = len (arr)
if (isProduct(arr,n, x) = = True ):
print ( "Yes" )
else :
print ( "No" )
x = 900
if (isProduct(arr, n, x)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool isProduct( int []arr,
int n, int x)
{
for ( int i = 0; i < n - 1; i++)
for ( int j = i + 1; j < n; j++)
if (arr[i] * arr[j] == x)
return true ;
return false ;
}
static void Main()
{
int []arr = {10, 20, 9, 40};
int x = 400;
int n = arr.Length;
if (isProduct(arr, n, x))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
x = 190;
if (isProduct(arr, n, x))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function isProduct(arr, n, x)
{
for ( var i=0; i<n-1; i++)
for ( var j=i+1; i<n; i++)
if (arr[i] * arr[j] == x)
return true ;
return false ;
}
var arr = [10, 20, 9, 40];
var x = 400;
var n = arr.length;
isProduct(arr, n, x)? document.write( "Yes<br>" )
: document.write( "No<br>" );
x = 190;
isProduct(arr, n, x)? document.write( "Yes" )
: document.write( "No" );
</script>
|
PHP
<?php
function isProduct( $arr , $n , $x )
{
for ( $i = 0;
$i < $n - 1; $i ++)
for ( $j = $i + 1;
$i < $n ; $i ++)
if ( $arr [ $i ] *
$arr [ $j ] == $x )
return true;
return false;
}
$arr = array (10, 20, 9, 40);
$x = 400;
$n = count ( $arr );
if (isProduct( $arr , $n , $x ))
echo "Yes\n" ;
else
echo "No\n" ;
$x = 190;
if (isProduct( $arr , $n , $x ))
echo "Yes\n" ;
else
echo "No\n" ;
?>
|
Time Complexity: O(n2)
Auxiliary Space: O(1)
Better Solution: We sort the given array. After sorting, we traverse the array and for every element arr[i], we do binary search for x/arr[i] in the subarray on the right of arr[i], i.e., in subarray arr[i+1..n-1]
C++
#include<bits/stdc++.h>
using namespace std;
bool binarysearch( int arr[], int n, int i, int x)
{
int l = 0, r = n - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (arr[mid]*arr[i] == x)
{
if (i!=mid)
{ return true ; }
else {
if (mid>0 && arr[mid-1]==arr[mid])
{ return true ; }
else if (mid<n-1 && arr[mid+1]==arr[mid])
{ return true ; }
else { return false ; }
}
}
else if (arr[mid]*arr[i] < x)
{
l = mid + 1;
}
else {
r = mid - 1;
}
}
return false ;
}
bool isProduct( int arr[], int n, int x)
{ sort( arr , arr+n);
for ( int i=0; i<n; i++)
{
if (binarysearch( arr, n, i , x))
{ return true ; }
}
return false ;
}
int main()
{
int arr[] = {10, 20, 9, 40};
int n = sizeof (arr)/ sizeof (arr[0]);
int x = 400;
if (isProduct(arr, n, x))
{ cout<< "Yes" <<endl; }
else { cout << "No" <<endl; }
x = 190;
if (isProduct(arr, n, x))
{ cout<< "Yes" <<endl; }
else { cout << "No" <<endl; }
return 0;
}
|
Java
import java.util.*;
public class Gfg {
public static boolean binarysearch( int [] arr, int n, int i, int x)
{
int l = 0 , r = n - 1 ;
while (l <= r) {
int mid = (l + r) / 2 ;
if (arr[mid]*arr[i] == x)
{
if (i!=mid)
{ return true ; }
else {
if (mid> 0 && arr[mid- 1 ]==arr[mid])
{ return true ; }
else if (mid<n- 1 && arr[mid+ 1 ]==arr[mid])
{ return true ; }
else { return false ; }
}
}
else if (arr[mid]*arr[i] < x)
{
l = mid + 1 ;
}
else {
r = mid - 1 ;
}
}
return false ;
}
public static boolean isProduct( int [] arr, int n, int x)
{ Arrays.sort(arr);
for ( int i= 0 ; i<n; i++)
{
if (binarysearch( arr, n, i , x))
{ return true ; }
}
return false ;
}
public static void main(String[] args)
{
int [] arr = { 10 , 20 , 9 , 40 };
int n = arr.length;
int x = 400 ;
if (isProduct(arr, n, x))
{ System.out.println( "Yes" ); }
else { System.out.println( "No" ); }
x = 190 ;
if (isProduct(arr, n, x))
{ System.out.println( "Yes" ); }
else { System.out.println( "No" ); }
}
}
|
Python3
def binarysearch(arr, n, i, x):
l = 0
r = n - 1
while l < = r:
mid = (l + r) / / 2
if arr[mid] * arr[i] = = x:
if i ! = mid:
return True
else :
if mid > 0 and arr[mid - 1 ] = = arr[mid]:
return True
elif mid < n - 1 and arr[mid + 1 ] = = arr[mid]:
return True
else :
return False
elif arr[mid] * arr[i] < x:
l = mid + 1
else :
r = mid - 1
return False
def isProduct(arr, n, x):
arr.sort()
for i in range (n):
if binarysearch(arr, n, i, x):
return True
return False
arr = [ 10 , 20 , 9 , 40 ]
n = len (arr)
x = 400
if isProduct(arr, n, x):
print ( "Yes" )
else :
print ( "No" )
x = 190
if isProduct(arr, n, x):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class Program
{
static bool binarysearch( int [] arr, int n, int i, int x)
{
int l = 0, r = n - 1;
while (l <= r)
{
int mid = (l + r) / 2;
if (arr[mid] * arr[i] == x)
{
if (i != mid)
{
return true ;
}
else
{
if (mid > 0 && arr[mid - 1] == arr[mid])
{
return true ;
}
else if (mid < n - 1 && arr[mid + 1] == arr[mid])
{
return true ;
}
else
{
return false ;
}
}
}
else if (arr[mid] * arr[i] < x)
{
l = mid + 1;
}
else
{
r = mid - 1;
}
}
return false ;
}
static bool isProduct( int [] arr, int n, int x)
{
Array.Sort(arr);
for ( int i = 0; i < n; i++)
{
if (binarysearch(arr, n, i, x))
{
return true ;
}
}
return false ;
}
static void Main()
{
int [] arr = { 10, 20, 9, 40 };
int n = arr.Length;
int x = 400;
if (isProduct(arr, n, x))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
x = 190;
if (isProduct(arr, n, x))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
function binarysearch(arr, n, i, x) {
let l = 0;
let r = n - 1;
while (l <= r) {
let mid = Math.floor((l + r) / 2);
if (arr[mid] * arr[i] == x) {
if (i != mid) {
return true ;
} else {
if (mid > 0 && arr[mid - 1] == arr[mid]) {
return true ;
} else if (mid < n - 1 && arr[mid + 1] == arr[mid]) {
return true ;
} else {
return false ;
}
}
} else if (arr[mid] * arr[i] < x) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return false ;
}
function isProduct(arr, n, x) {
arr.sort();
for (let i = 0; i < n; i++) {
if (binarysearch(arr, n, i, x)) {
return true ;
}
}
return false ;
}
let arr = [10, 20, 9, 40];
let n = arr.length;
let x = 400;
if (isProduct(arr, n, x)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
x = 190;
if (isProduct(arr, n, x)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
Time Complexity: O(n log n)
Auxiliary Space: O(1)
Another Approach ( Using two pointer technique):
This approach to solve the problem is to sort the array in ascending order and then use Two pointer approach ( l = 0, r = arr.size()-1) to traverse that sorted array. If product of arr[l] and arr[r] is equal to x, then return true. If product is less than k then increase l else decrease r.
Algorithm:
- Define a function isProduct that takes an integer array arr, an integer n, and an integer x as inputs and returns a boolean value. The function first sorts the array arr in ascending order. It then initializes two indices l and r to the beginning and end of the array, respectively. While l < r, the function calculates the product of the elements at indices l and r, compares it with x, and adjusts l and r accordingly. If the product equals x, it returns true. Otherwise, if the product is less than x, it increments l to increase the value of the product, and if the product is greater than x, it decrements r to decrease the value of the product. If no such pair exists in the array, the function returns false.
- In the main function:
a. Create an integer array according to the input specification.
b. Initialize an integer n as the size of the array.
c. Initialize an integer x according to the input specification.
d. Call the isProduct function with the array, n, and x as inputs.
e. Print “Yes” if the function returns true, and “No” otherwise.
Below is the implementation of the above idea:
C++
#include <bits/stdc++.h>
using namespace std;
bool isProduct( int arr[], int n, int x) {
sort(arr, arr + n);
int l = 0, r = n - 1;
while (l < r) {
int prod = arr[l] * arr[r];
if (prod == x) {
return true ;
}
else if (prod < x)
l++;
else
r--;
}
return false ;
}
int main() {
int arr[] = { 10, 20, 9, 40 };
int n = sizeof (arr) / sizeof (arr[0]);
int x = 400;
if (isProduct(arr, n, x)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
x = 190;
if (isProduct(arr, n, x)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
|
Java
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int [] arr = { 10 , 20 , 9 , 40 };
int n = arr.length;
int x = 400 ;
if (isProduct(arr, n, x)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
x = 190 ;
if (isProduct(arr, n, x)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
}
static boolean isProduct( int [] arr, int n, int x) {
Arrays.sort(arr);
int l = 0 , r = n - 1 ;
while (l < r) {
int prod = arr[l] * arr[r];
if (prod == x) {
return true ;
}
else if (prod < x) {
l++;
}
else {
r--;
}
}
return false ;
}
}
|
Python3
def isProduct(arr, n, x):
arr.sort()
l, r = 0 , n - 1
while l < r:
prod = arr[l] * arr[r]
if prod = = x:
return True
elif prod < x:
l + = 1
else :
r - = 1
return False
arr = [ 10 , 20 , 9 , 40 ]
n = len (arr)
x = 400
if isProduct(arr, n, x):
print ( "Yes" )
else :
print ( "No" )
x = 190
if isProduct(arr, n, x):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
public class GFG{
public static bool isProduct( int [] arr, int n, int x)
{
Array.Sort(arr);
int l = 0, r = n - 1;
while (l < r)
{
int prod = arr[l] * arr[r];
if (prod == x)
{
return true ;
}
else if (prod < x)
{
l++;
}
else
{
r--;
}
}
return false ;
}
public static void Main()
{
int [] arr = { 10, 20, 9, 40 };
int n = arr.Length;
int x = 400;
if (isProduct(arr, n, x))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
x = 190;
if (isProduct(arr, n, x))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
function isProduct( arr, n, x) {
arr.sort((a, b) => a - b);
let l = 0, r = n - 1;
while (l < r) {
let prod = arr[l] * arr[r];
if (prod == x) {
return true ;
}
else if (prod < x)
l++;
else
r--;
}
return false ;
}
let arr = [10, 20, 9, 40 ];
let n = arr.length;
let x = 400;
if (isProduct(arr, n, x)) {
console.log( "Yes" );
}
else {
console.log( "No" );
}
x = 190;
if (isProduct(arr, n, x)) {
console.log( "Yes" );
}
else {
console.log( "No" );
}
|
Time Complexity: O(N * logN) where N is size of input array. This is because sort has been called which takes N*logN time.
Space Complexity: O(1) as no extra space has been taken.
Efficient Solution: We can improve time complexity to O(n) using hashing. Below are the steps.
- Create an empty hash table
- Traverse array elements and do the following for every element arr[i].
- If arr[i] is 0 and x is also 0, return true, else ignore arr[i].
- If x % arr[i] is 0 and x/arr[i] exists in the table, it returns true.
- Insert arr[i] into the hash table.
- Return false
Below is the implementation of the above idea.
C++14
#include<bits/stdc++.h>
using namespace std;
bool isProduct( int arr[], int n, int x)
{
if (n < 2)
return false ;
unordered_set< int > s;
for ( int i=0; i<n; i++)
{
if (arr[i] == 0)
{
if (x == 0)
return true ;
else
continue ;
}
if (x%arr[i] == 0)
{
if (s.find(x/arr[i]) != s.end())
return true ;
s.insert(arr[i]);
}
}
return false ;
}
int main()
{
int arr[] = {10, 20, 9, 40};
int x = 400;
int n = sizeof (arr)/ sizeof (arr[0]);
isProduct(arr, n, x)? cout << "Yes\n"
: cout << "No" ;
x = 190;
isProduct(arr, n, x)? cout << "Yes\n"
: cout << "No" ;
return 0;
}
|
Java
import java.util.HashSet;
class GFG
{
static boolean isProduct( int arr[], int n, int x)
{
HashSet<Integer> hset = new HashSet<>();
if (n < 2 )
return false ;
for ( int i = 0 ; i < n; i++)
{
if (arr[i] == 0 )
{
if (x == 0 )
return true ;
else
continue ;
}
if (x % arr[i] == 0 )
{
if (hset.contains(x / arr[i]))
return true ;
hset.add(arr[i]);
}
}
return false ;
}
public static void main(String[] args)
{
int arr[] = { 10 , 20 , 9 , 40 };
int x = 400 ;
int n = arr.length;
if (isProduct(arr, arr.length, x))
System.out.println( "Yes" );
else
System.out.println( "No" );
x = 190 ;
if (isProduct(arr, arr.length, x))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isProduct(arr, n, x):
if n < 2 :
return False
s = set ()
for i in range ( 0 , n):
if arr[i] = = 0 :
if x = = 0 :
return True
else :
continue
if x % arr[i] = = 0 :
if x / / arr[i] in s:
return True
s.add(arr[i])
return False
if __name__ = = "__main__" :
arr = [ 10 , 20 , 9 , 40 ]
x = 400
n = len (arr)
if isProduct(arr, n, x):
print ( "Yes" )
else :
print ( "No" )
x = 190
if isProduct(arr, n, x):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static bool isProduct( int [] arr,
int n, int x)
{
HashSet< int > hset = new HashSet< int >();
if (n < 2)
{
return false ;
}
for ( int i = 0; i < n; i++)
{
if (arr[i] == 0)
{
if (x == 0)
{
return true ;
}
else
{
continue ;
}
}
if (x % arr[i] == 0)
{
if (hset.Contains(x / arr[i]))
{
return true ;
}
hset.Add(arr[i]);
}
}
return false ;
}
public static void Main( string [] args)
{
int [] arr = new int [] {10, 20, 9, 40};
int x = 400;
int n = arr.Length;
if (isProduct(arr, arr.Length, x))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
x = 190;
if (isProduct(arr, arr.Length, x))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
function isProduct(arr, n, x)
{
let hset = new Set();
if (n < 2)
return false ;
for (let i = 0; i < n; i++)
{
if (arr[i] == 0)
{
if (x == 0)
return true ;
else
continue ;
}
if (x % arr[i] == 0)
{
if (hset.has(x / arr[i]))
return true ;
hset.add(arr[i]);
}
}
return false ;
}
let arr = [10, 20, 9, 40];
let x = 400;
let n = arr.length;
if (isProduct(arr, arr.length, x))
document.write( "Yes" + "<br/>" );
else
document.write( "No" + "<br/>" );
x = 190;
if (isProduct(arr, arr.length, x))
document.write( "Yes" + "<br/>" );
else
document.write( "No" + "<br/>" );
</script>
|
Time Complexity : O(n)
Auxiliary Space: O(n)
In the next set, we will be discussing approaches to print all pairs with products equal to 0.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...