📌  相关文章
📜  计算乘积10 ^ 9 + 7等于1的对

📅  最后修改于: 2021-05-14 02:23:44             🧑  作者: Mango

给定数组arr [] ,任务是计算给定数组中无序对(arr [i],arr [j])的数量,以使(arr [i] * arr [j])%10 9 + 7等于1

例子:

天真的方法:解决问题的最简单方法是遍历数组并从给定数组生成所有可能的对。对于每对,计算其乘积为10 9 + 7 。如果发现等于1 ,则增加此类对的计数。最后,打印获得的最终计数

时间复杂度: O(N 2 )
辅助空间: O(N)

高效方法:要优化上述方法,请使用以下属性,如果(arr [i] * arr [j])%1000000007 = 1 ,则arr [j]是模10 9 + 7下的arr [i]的模逆。永远是独一无二的。请按照以下步骤解决问题:

  • 初始化Map哈希,以将每个元素的频率存储在数组arr []中
  • 初始化变量pairCount ,以存储所需对的计数。
  • 遍历数组并计算modularInverse是逆ARR [I]的下10 9 + 7并且由散列[modularInverse]增加pairCount和减1 pairCount的计数,如果modularInverse被发现是等于给Arr [i]中
  • 最后,打印对数Count / 2作为必需的答案,因为上述方法对每一对都进行了两次计数。

下面是上述方法的实现:

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


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
static final int MOD = 1000000007;
 
// Iterative Function to calculate (x^y) % MOD
static long modPower(long x, int y)
{
     
    // Initialize result
    long res = 1;
 
    // Update x if it exceeds MOD
    x = x % MOD;
 
    // If x is divisible by MOD
    if (x == 0)
        return 0;
 
    while (y > 0)
    {
         
        // If y is odd
        if (y % 2 == 1)
         
            // Multiply x with res
            res = (res * x) % MOD;
 
        // y must be even now
        y = y / 2;
        x = (x * x) % MOD;
    }
    return res;
}
 
// Function to count number of pairs
// whose product modulo 1000000007 is 1
static int countPairs(long arr[], int N)
{
     
    // Stores the count of
    // desired pairs
    int pairCount = 0;
 
    // Stores the frequencies of
    // each array element
    HashMap hash = new HashMap<>();
 
    // Traverse the array and update
    // frequencies in hash
    for(int i = 0; i < N; i++)
    {
        if (hash.containsKey(arr[i]))
        {
            hash.put(arr[i], hash.get(arr[i]) + 1);
        }
        else
        {
            hash.put(arr[i], 1);
        }
    }
     
    for(int i = 0; i < N; i++)
    {
         
        // Calculate modular inverse of
        // arr[i] under modulo 1000000007
        long modularInverse = modPower(arr[i],
                                       MOD - 2);
 
        // Update desired count of pairs
        if (hash.containsKey(modularInverse))
            pairCount += hash.get(modularInverse);
         
        // If arr[i] and its modular inverse
        // is equal under modulo MOD
        if (arr[i] == modularInverse)
        {
             
            // Updating count of desired pairs
            pairCount--;
        }
    }
 
    // Return the final count
    return pairCount / 2;
}
 
// Driver code
public static void main(String[] args)
{
    long arr[] = { 2, 236426, 280311812, 500000004 };
    int N = arr.length;
 
    System.out.print(countPairs(arr, N));
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program to implement
# the above approach
from collections import defaultdict
MOD = 1000000007
 
# Iterative Function to
# calculate (x^y) % MOD
def modPower(x, y):
 
    # Initialize result
    res = 1
 
    # Update x if it exceeds
    # MOD
    x = x % MOD
 
    # If x is divisible by
    # MOD
    if (x == 0):
        return 0
 
    while (y > 0):
 
        # If y is odd
        if (y & 1):
 
            # Multiply x with res
            res = (res * x) % MOD
 
        # y must be even now
        y = y // 2
        x = (x * x) % MOD
 
    return res
 
# Function to count number
# of pairs whose product
# modulo 1000000007 is 1
def countPairs(arr, N):
 
    # Stores the count of
    # desired pairs
    pairCount = 0
 
    # Stores the frequencies of
    # each array element
    hash1 = defaultdict(int)
 
    # Traverse the array and
    # update frequencies in hash
    for i in range(N):
        hash1[arr[i]] += 1
 
    for i in range(N):
 
        # Calculate modular inverse
        # of arr[i] under modulo
        # 1000000007
        modularInverse = modPower(arr[i],
                                  MOD - 2)
 
        # Update desired count of pairs
        pairCount += hash1[modularInverse]
 
        # If arr[i] and its modular
        # inverse is equal under
        # modulo MOD
        if (arr[i] == modularInverse):
 
            # Updating count of
            # desired pairs
            pairCount -= 1
 
    # Return the final count
    return pairCount // 2
 
# Driver code
if __name__ == "__main__":
 
    arr = [2, 236426,
           280311812,
           500000004]
    N = len(arr)
    print(countPairs(arr, N))
 
# This code is contributed by Chitranayal


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
static int MOD = 1000000007;
 
// Iterative Function to calculate (x^y) % MOD
static long modPower(long x, int y)
{
     
    // Initialize result
    long res = 1;
 
    // Update x if it exceeds MOD
    x = x % MOD;
 
    // If x is divisible by MOD
    if (x == 0)
        return 0;
 
    while (y > 0)
    {
         
        // If y is odd
        if (y % 2 == 1)
         
            // Multiply x with res
            res = (res * x) % MOD;
 
        // y must be even now
        y = y / 2;
        x = (x * x) % MOD;
    }
    return res;
}
 
// Function to count number of pairs
// whose product modulo 1000000007 is 1
static int countPairs(long []arr, int N)
{
     
    // Stores the count of
    // desired pairs
    int pairCount = 0;
 
    // Stores the frequencies of
    // each array element
    Dictionary hash = new Dictionary();
 
    // Traverse the array and update
    // frequencies in hash
    for(int i = 0; i < N; i++)
    {
        if (hash.ContainsKey(arr[i]))
        {
            hash.Add(arr[i], hash[arr[i]] + 1);
        }
        else
        {
            hash.Add(arr[i], 1);
        }
    }
     
    for(int i = 0; i < N; i++)
    {
         
        // Calculate modular inverse of
        // arr[i] under modulo 1000000007
        long modularInverse = modPower(arr[i],
                                       MOD - 2);
 
        // Update desired count of pairs
        if (hash.ContainsKey(modularInverse))
            pairCount += hash[modularInverse];
         
        // If arr[i] and its modular inverse
        // is equal under modulo MOD
        if (arr[i] == modularInverse)
        {
             
            // Updating count of desired pairs
            pairCount--;
        }
    }
 
    // Return the final count
    return pairCount / 2;
}
 
// Driver code
public static void Main()
{
    long []arr = { 2, 236426, 280311812, 500000004 };
    int N = arr.Length;
 
    Console.WriteLine(countPairs(arr, N));
}
}
 
// This code is contributed by bgangwar59


输出:
2

时间复杂度: O(NlogN)
辅助空间: O(N)