Find all pairs (a,b) and (c,d) in array which satisfy ab = cd in C++

C++Server Side ProgrammingProgramming

<p>Suppose we have an array A, from that array, we have to choose two pairs (a, b) and (c, d), such that ab = cd. Let the array A = [3, 4, 7, 1, 2, 9, 8]. The output pairs are (4, 2) and (1, 8). To solve this, we will follow these steps &minus;</p><ul class="list"><li>For i := 0 to n-1, do<ul class="list"><li>for j := i + 1 to n-1, do<ul class="list"><li>get product = arr[i] * arr[j]</li><li>if product is not present in the hash table, then Hash[product] := (i, j)</li><li>if product is present in the hash table, then print previous and current elements.</li></ul></li></ul></li></ul><h2>Example</h2><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include &lt;iostream&gt; #include &lt;unordered_map&gt; using namespace std; void displayPairs(int arr[], int n) { &nbsp; &nbsp;bool found = false; &nbsp; &nbsp;unordered_map&lt;int, pair &lt; int, int &gt; &gt; Hash; &nbsp; &nbsp;for (int i=0; i&lt;n; i++) { &nbsp; &nbsp; &nbsp; for (int j=i+1; j&lt;n; j++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int prod = arr[i]*arr[j]; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (Hash.find(prod) == Hash.end()) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Hash[prod] = make_pair(i,j); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pair&lt;int,int&gt; pp = Hash[prod]; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cout &lt;&lt; &quot;(&quot; &lt;&lt; arr[pp.first] &lt;&lt; &quot;, &quot; &lt;&lt; arr[pp.second] &lt;&lt; &quot;) and (&quot; &lt;&lt; arr[i]&lt;&lt;&quot;, &quot;&lt;&lt;arr[j] &lt;&lt; &quot;)&quot;&lt;&lt;endl; found = true; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;if (found == false) &nbsp; &nbsp;cout &lt;&lt; &quot;No pairs have Found&quot; &lt;&lt; endl; } int main() { &nbsp; &nbsp;int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; &nbsp; &nbsp;int n = sizeof(arr)/sizeof(int); &nbsp; &nbsp;displayPairs(arr, n); }</pre><h2>Output</h2><pre class="result notranslate">(1, 6) and (2, 3) (1, 8) and (2, 4) (2, 6) and (3, 4) (3, 8) and (4, 6)</pre>
Updated on 24-Oct-2019 13:23:15