Count pairs whose product modulo 10 ^ 9 + 7 is equal to 1 | C ++ program to implement the above approach ; Iterative Function to calculate ( x ^ y ) % MOD ; Initialize result ; Update x if it exceeds MOD ; If x is divisible by MOD ; If y is odd ; Multiply x with res ; y must be even now ; Function to count number of pairs whose product modulo 1000000007 is 1 ; Stores the count of desired pairs ; Stores the frequencies of each array element ; Traverse the array and update frequencies in hash ; Calculate modular inverse of arr [ i ] under modulo 1000000007 ; Update desired count of pairs ; If arr [ i ] and its modular inverse is equal under modulo MOD ; Updating count of desired pairs ; Return the final count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD  1000000007 NEW_LINE long long int modPower ( long long int x , long long int y ) { long long int res = 1 ; x = x % MOD ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % MOD ; y = y / 2 ; x = ( x * x ) % MOD ; } return res ; } int countPairs ( long long int arr [ ] , int N ) { int pairCount = 0 ; map < long long int , int > hash ; for ( int i = 0 ; i < N ; i ++ ) { hash [ arr [ i ] ] ++ ; } for ( int i = 0 ; i < N ; i ++ ) { long long int modularInverse = modPower ( arr [ i ] , MOD - 2 ) ; pairCount += hash [ modularInverse ] ; if ( arr [ i ] == modularInverse ) { pairCount -- ; } } return pairCount / 2 ; } int main ( ) { long long int arr [ ] = { 2 , 236426 , 280311812 , 500000004 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; }