📜  计算数组中的双素数对

📅  最后修改于: 2021-05-05 02:43:32             🧑  作者: Mango

给定N个自然数的数组arr [] 。任务是计算arr []中所有可能为Twin Prime的对。

双质数是那些数,并且两个质数之间相差两(2)的那些数。换句话说,孪生素数是素数差距为2的素数。

例子:

天真的方法:
这个想法是在给定数组arr []中找到所有可能的对,并检查对中的两个元素是否都是素数,并且它们相差2 ,则当前对形成双素数。

下面是上述方法的实现:

C++
// C++ program to count Twin
// Prime pairs in array
#include 
using namespace std;
  
// A utility function to check if
// the number n is prime or not
bool isPrime(int n)
{
    // Base Cases
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
  
    // Check to skip middle five
    // numbers in below loop
    if (n % 2 == 0 || n % 3 == 0)
        return false;
  
    for (int i = 5; i * i <= n; i += 6) {
  
        // If n is divisible by i and i+2
        // then it is not prime
        if (n % i == 0 || n % (i + 2) == 0) {
            return false;
        }
    }
  
    return true;
}
  
// A utility function that check
// if n1 and n2 are Twin Primes
// or not
bool twinPrime(int n1, int n2)
{
    return (isPrime(n1)
            && isPrime(n2)
            && abs(n1 - n2) == 2);
}
  
// Function to find Twin Prime
// pairs from the given array
int countTwinPairs(int arr[], int n)
{
    int count = 0;
  
    // Iterate through all pairs
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
  
            // Increment count if
            // twin prime pair
            if (twinPrime(arr[i], arr[j])) {
                count++;
            }
        }
    }
  
    return count;
}
  
// Driver's code
int main()
{
    int arr[] = { 2, 3, 5, 11 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call to find
    // Twin Primes pair
    cout << countTwinPairs(arr, n);
    return 0;
}


Java
// Java program to count Twin
// Prime pairs in array
import java.util.*;
  
class GFG{
   
// A utility function to check if
// the number n is prime or not
static boolean isPrime(int n)
{
    // Base Cases
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
   
    // Check to skip middle five
    // numbers in below loop
    if (n % 2 == 0 || n % 3 == 0)
        return false;
   
    for (int i = 5; i * i <= n; i += 6) {
   
        // If n is divisible by i and i+2
        // then it is not prime
        if (n % i == 0 || n % (i + 2) == 0) {
            return false;
        }
    }
   
    return true;
}
   
// A utility function that check
// if n1 and n2 are Twin Primes
// or not
static boolean twinPrime(int n1, int n2)
{
    return (isPrime(n1)
            && isPrime(n2)
            && Math.abs(n1 - n2) == 2);
}
   
// Function to find Twin Prime
// pairs from the given array
static int countTwinPairs(int arr[], int n)
{
    int count = 0;
   
    // Iterate through all pairs
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
   
            // Increment count if
            // twin prime pair
            if (twinPrime(arr[i], arr[j])) {
                count++;
            }
        }
    }
   
    return count;
}
   
// Driver's code
public static void main(String[] args)
{
    int arr[] = { 2, 3, 5, 11 };
    int n = arr.length;
   
    // Function call to find
    // Twin Primes pair
    System.out.print(countTwinPairs(arr, n));
}
}
  
// This code is contributed by Rajput-Ji


Python 3
# Python 3 program to count Twin
# Prime pairs in array
from math import sqrt
  
# A utility function to check if
# the number n is prime or not
def isPrime(n):
      
    # Base Cases
    if (n <= 1):
        return False
    if (n <= 3):
        return True
  
    # Check to skip middle five
    # numbers in below loop
    if (n % 2 == 0 or n % 3 == 0):
        return False
  
    for i in range(5,int(sqrt(n))+1,6):
          
        # If n is divisible by i and i+2
        # then it is not prime
        if (n % i == 0 or n % (i + 2) == 0):
            return False
  
    return True
  
# A utility function that check
# if n1 and n2 are Twin Primes
# or not
def twinPrime(n1, n2):
    return (isPrime(n1) and isPrime(n2) and abs(n1 - n2) == 2)
  
# Function to find Twin Prime
# pairs from the given array
def countTwinPairs(arr, n):
    count = 0
  
    # Iterate through all pairs
    for i in range(n):
        for j in range(i + 1,n):
              
            # Increment count if
            # twin prime pair
            if (twinPrime(arr[i], arr[j])):
                count += 1
  
    return count
  
# Driver's code
if __name__ == '__main__':
    arr = [2, 3, 5, 11]
    n = len(arr)
  
    # Function call to find
    # Twin Primes pair
    print(countTwinPairs(arr, n))
  
# This code is contributed by Surendra_Gangwar


C#
// C# program to count Twin
// Prime pairs in array
using System;
  
class GFG{
    
// A utility function to check if
// the number n is prime or not
static bool isPrime(int n)
{
    // Base Cases
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
    
    // Check to skip middle five
    // numbers in below loop
    if (n % 2 == 0 || n % 3 == 0)
        return false;
    
    for (int i = 5; i * i <= n; i += 6) {
    
        // If n is divisible by i and i+2
        // then it is not prime
        if (n % i == 0 || n % (i + 2) == 0) {
            return false;
        }
    }
    
    return true;
}
    
// A utility function that check
// if n1 and n2 are Twin Primes
// or not
static bool twinPrime(int n1, int n2)
{
    return (isPrime(n1)
            && isPrime(n2)
            && Math.Abs(n1 - n2) == 2);
}
    
// Function to find Twin Prime
// pairs from the given array
static int countTwinPairs(int []arr, int n)
{
    int count = 0;
    
    // Iterate through all pairs
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
    
            // Increment count if
            // twin prime pair
            if (twinPrime(arr[i], arr[j])) {
                count++;
            }
        }
    }
    
    return count;
}
    
// Driver's code
public static void Main(String[] args)
{
    int []arr = { 2, 3, 5, 11 };
    int n = arr.Length;
    
    // Function call to find
    // Twin Primes pair
    Console.Write(countTwinPairs(arr, n));
}
}
  
// This code is contributed by 29AjayKumar


C/C++
// C++ program to count Twin
// Prime pairs in array
#include 
using namespace std;
  
// To store check the prime
// number
vector Prime;
  
// A utility function that find
// the Prime Numbers till N
void computePrime(int N)
{
  
    // Resize the Prime Number
    Prime.resize(N + 1, true);
    Prime[0] = Prime[1] = false;
  
    // Loop till sqrt(N) to find
    // prime numbers and make their
    // multiple false in the bool
    // array Prime
    for (int i = 2; i * i <= N; i++) {
        if (Prime[i]) {
            for (int j = i * i; j < N; j += i) {
                Prime[j] = false;
            }
        }
    }
}
  
// Function that returns the count
// of Twin Prime Pairs
int countTwinPairs(int arr[], int n)
{
  
    // Find the maximum element in
    // the given array arr[]
    int maxE = *max_element(arr, arr + n);
  
    // Function to calculate the
    // prime numbers till N
    computePrime(maxE);
  
    // To store the count of pairs
    int count = 0;
  
    // To store the frequency of
    // element in the array arr[]
    int freq[maxE + 1] = { 0 };
  
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
  
    // Sort before traversing the array
    sort(arr, arr + n);
  
    // Traverse the array and find
    // the pairs with Twin Primes
    for (int i = 0; i < n; i++) {
  
        // If current element is
        // Prime, then check for
        // (current element + 2)
        if (Prime[arr[i]]) {
            if (freq[arr[i] + 2] > 0
                && Prime[arr[i] + 2]) {
                count++;
            }
        }
    }
  
    // Return the count of pairs
    return count;
}
  
// Driver's code
int main()
{
    int arr[] = { 2, 4, 3, 5, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call to find
    // Twin Primes pair
    cout << countTwinPairs(arr, n);
    return 0;
}


Java
// Java program to count Twin
// Prime pairs in array
  
import java.util.*;
  
class GFG{
   
// To store check the prime
// number
static boolean []Prime;
   
// A utility function that find
// the Prime Numbers till N
static void computePrime(int N)
{
   
    // Resize the Prime Number
    Prime = new boolean[N + 1];
    Arrays.fill(Prime, true);
    Prime[0] = Prime[1] = false;
   
    // Loop till Math.sqrt(N) to find
    // prime numbers and make their
    // multiple false in the bool
    // array Prime
    for (int i = 2; i * i <= N; i++) {
        if (Prime[i]) {
            for (int j = i * i; j < N; j += i) {
                Prime[j] = false;
            }
        }
    }
}
   
// Function that returns the count
// of Twin Prime Pairs
static int countTwinPairs(int arr[], int n)
{
   
    // Find the maximum element in
    // the given array arr[]
    int maxE = Arrays.stream(arr).max().getAsInt();
   
    // Function to calculate the
    // prime numbers till N
    computePrime(maxE);
   
    // To store the count of pairs
    int count = 0;
   
    // To store the frequency of
    // element in the array arr[]
    int freq[] = new int[maxE + 1];
   
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
   
    // Sort before traversing the array
    Arrays.sort(arr);
   
    // Traverse the array and find
    // the pairs with Twin Primes
    for (int i = 0; i < n; i++) {
   
        // If current element is
        // Prime, then check for
        // (current element + 2)
        if (Prime[arr[i]]) {
            if (arr[i] + 2 < freq.length && freq[arr[i] + 2] > 0
                && Prime[arr[i] + 2]) {
                count++;
            }
        }
    }
   
    // Return the count of pairs
    return count;
}
   
// Driver's code
public static void main(String[] args)
{
    int arr[] = { 2, 4, 3, 5, 7 };
    int n = arr.length;
   
    // Function call to find
    // Twin Primes pair
    System.out.print(countTwinPairs(arr, n));
}
}
  
// This code is contributed by PrinciRaj1992


Python3
# Python 3 program to count Twin
# Prime pairs in array
  
# A utility function that find
# the Prime Numbers till N
def computePrime( N):
  
    # Resize the Prime Number
    Prime = [True]*(N + 1)
    Prime[0] = False
    Prime[1] = False
  
    # Loop till sqrt(N) to find
    # prime numbers and make their
    # multiple false in the bool
    # array Prime
    i = 2
    while i * i <= N:
        if (Prime[i]):
            for j in range( i * i, N, i):
                Prime[j] = False
        i += 1
  
    return Prime
  
# Function that returns the count
# of Twin Prime Pairs
def countTwinPairs(arr, n):
  
    # Find the maximum element in
    # the given array arr[]
    maxE = max(arr)
  
    # Function to calculate the
    # prime numbers till N
    Prime = computePrime(maxE)
  
    # To store the count of pairs
    count = 0
  
    # To store the frequency of
    # element in the array arr[]
    freq = [0]*(maxE + 2)
  
    for i in range( n):
        freq[arr[i]] += 1
  
    # Sort before traversing the array
    arr.sort()
  
    # Traverse the array and find
    # the pairs with Twin Primes
    for i in range(n):
  
        # If current element is
        # Prime, then check for
        # (current element + 2)
        if (Prime[arr[i]]):
            if ((arr[i] + 2) <= (maxE) and freq[arr[i] + 2] > 0
                and Prime[arr[i] + 2]):
                count += 1
  
    # Return the count of pairs
    return count
  
# Driver's code
if __name__ == "__main__":
      
    arr = [ 2, 4, 3, 5, 7 ]
    n = len(arr)
  
    # Function call to find
    # Twin Primes pair
    print( countTwinPairs(arr, n))
      
# This code is contributed by chitranayal


C#
// C# program to count Twin
// Prime pairs in array
using System;
using System.Linq;
  
class GFG{
    
// To store check the prime
// number
static bool []Prime;
    
// A utility function that find
// the Prime Numbers till N
static void computePrime(int N)
{
    
    // Resize the Prime Number
    Prime = new bool[N + 1];
    for (int i = 0; i  <= N; i++){
        Prime[i] = true;    
    }
  
    Prime[0] = Prime[1] = false;
    
    // Loop till Math.Sqrt(N) to find
    // prime numbers and make their
    // multiple false in the bool
    // array Prime
    for (int i = 2; i * i <= N; i++) {
        if (Prime[i]) {
            for (int j = i * i; j < N; j += i) {
                Prime[j] = false;
            }
        }
    }
}
    
// Function that returns the count
// of Twin Prime Pairs
static int countTwinPairs(int []arr, int n)
{
    
    // Find the maximum element in
    // the given array []arr
    int maxE = arr.Max();
    
    // Function to calculate the
    // prime numbers till N
    computePrime(maxE);
    
    // To store the count of pairs
    int count = 0;
    
    // To store the frequency of
    // element in the array []arr
    int []freq = new int[maxE + 1];
    
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
    
    // Sort before traversing the array
    Array.Sort(arr);
    
    // Traverse the array and find
    // the pairs with Twin Primes
    for (int i = 0; i < n; i++) {
    
        // If current element is
        // Prime, then check for
        // (current element + 2)
        if (Prime[arr[i]]) {
            if (arr[i] + 2 < freq.Length && freq[arr[i] + 2] > 0
                && Prime[arr[i] + 2]) {
                count++;
            }
        }
    }
    
    // Return the count of pairs
    return count;
}
    
// Driver's code
public static void Main(String[] args)
{
    int []arr = { 2, 4, 3, 5, 7 };
    int n = arr.Length;
    
    // Function call to find
    // Twin Primes pair
    Console.Write(countTwinPairs(arr, n));
}
}
   
// This code is contributed by PrinciRaj1992


输出:
1

时间复杂度: O(sqrt(M)* N 2 ),其中N是给定数组中元素的数量,M是数组中最大的元素。

高效方法:

  1. 使用Eratosthenes筛子对给定数组arr []中的所有素数进行预计算,直到最大数。
  2. 存储给定数组arr []的所有元素的所有频率。
  3. 对给定数组arr []进行排序。
  4. 对于数组中的每个元素,请检查该元素是否为质数。
  5. 如果元素是素数,则检查(element + 2)是否是素数,是否存在于给定数组arr []中
  6. 如果存在(element + 2),则(element + 2)的频率将给出当前元素的对数。
  7. 对数组中的所有元素重复上述步骤。

    下面是上述方法的实现:

    C / C++

    // C++ program to count Twin
    // Prime pairs in array
    #include 
    using namespace std;
      
    // To store check the prime
    // number
    vector Prime;
      
    // A utility function that find
    // the Prime Numbers till N
    void computePrime(int N)
    {
      
        // Resize the Prime Number
        Prime.resize(N + 1, true);
        Prime[0] = Prime[1] = false;
      
        // Loop till sqrt(N) to find
        // prime numbers and make their
        // multiple false in the bool
        // array Prime
        for (int i = 2; i * i <= N; i++) {
            if (Prime[i]) {
                for (int j = i * i; j < N; j += i) {
                    Prime[j] = false;
                }
            }
        }
    }
      
    // Function that returns the count
    // of Twin Prime Pairs
    int countTwinPairs(int arr[], int n)
    {
      
        // Find the maximum element in
        // the given array arr[]
        int maxE = *max_element(arr, arr + n);
      
        // Function to calculate the
        // prime numbers till N
        computePrime(maxE);
      
        // To store the count of pairs
        int count = 0;
      
        // To store the frequency of
        // element in the array arr[]
        int freq[maxE + 1] = { 0 };
      
        for (int i = 0; i < n; i++) {
            freq[arr[i]]++;
        }
      
        // Sort before traversing the array
        sort(arr, arr + n);
      
        // Traverse the array and find
        // the pairs with Twin Primes
        for (int i = 0; i < n; i++) {
      
            // If current element is
            // Prime, then check for
            // (current element + 2)
            if (Prime[arr[i]]) {
                if (freq[arr[i] + 2] > 0
                    && Prime[arr[i] + 2]) {
                    count++;
                }
            }
        }
      
        // Return the count of pairs
        return count;
    }
      
    // Driver's code
    int main()
    {
        int arr[] = { 2, 4, 3, 5, 7 };
        int n = sizeof(arr) / sizeof(arr[0]);
      
        // Function call to find
        // Twin Primes pair
        cout << countTwinPairs(arr, n);
        return 0;
    }
    

    Java

    // Java program to count Twin
    // Prime pairs in array
      
    import java.util.*;
      
    class GFG{
       
    // To store check the prime
    // number
    static boolean []Prime;
       
    // A utility function that find
    // the Prime Numbers till N
    static void computePrime(int N)
    {
       
        // Resize the Prime Number
        Prime = new boolean[N + 1];
        Arrays.fill(Prime, true);
        Prime[0] = Prime[1] = false;
       
        // Loop till Math.sqrt(N) to find
        // prime numbers and make their
        // multiple false in the bool
        // array Prime
        for (int i = 2; i * i <= N; i++) {
            if (Prime[i]) {
                for (int j = i * i; j < N; j += i) {
                    Prime[j] = false;
                }
            }
        }
    }
       
    // Function that returns the count
    // of Twin Prime Pairs
    static int countTwinPairs(int arr[], int n)
    {
       
        // Find the maximum element in
        // the given array arr[]
        int maxE = Arrays.stream(arr).max().getAsInt();
       
        // Function to calculate the
        // prime numbers till N
        computePrime(maxE);
       
        // To store the count of pairs
        int count = 0;
       
        // To store the frequency of
        // element in the array arr[]
        int freq[] = new int[maxE + 1];
       
        for (int i = 0; i < n; i++) {
            freq[arr[i]]++;
        }
       
        // Sort before traversing the array
        Arrays.sort(arr);
       
        // Traverse the array and find
        // the pairs with Twin Primes
        for (int i = 0; i < n; i++) {
       
            // If current element is
            // Prime, then check for
            // (current element + 2)
            if (Prime[arr[i]]) {
                if (arr[i] + 2 < freq.length && freq[arr[i] + 2] > 0
                    && Prime[arr[i] + 2]) {
                    count++;
                }
            }
        }
       
        // Return the count of pairs
        return count;
    }
       
    // Driver's code
    public static void main(String[] args)
    {
        int arr[] = { 2, 4, 3, 5, 7 };
        int n = arr.length;
       
        // Function call to find
        // Twin Primes pair
        System.out.print(countTwinPairs(arr, n));
    }
    }
      
    // This code is contributed by PrinciRaj1992
    

    Python3

    # Python 3 program to count Twin
    # Prime pairs in array
      
    # A utility function that find
    # the Prime Numbers till N
    def computePrime( N):
      
        # Resize the Prime Number
        Prime = [True]*(N + 1)
        Prime[0] = False
        Prime[1] = False
      
        # Loop till sqrt(N) to find
        # prime numbers and make their
        # multiple false in the bool
        # array Prime
        i = 2
        while i * i <= N:
            if (Prime[i]):
                for j in range( i * i, N, i):
                    Prime[j] = False
            i += 1
      
        return Prime
      
    # Function that returns the count
    # of Twin Prime Pairs
    def countTwinPairs(arr, n):
      
        # Find the maximum element in
        # the given array arr[]
        maxE = max(arr)
      
        # Function to calculate the
        # prime numbers till N
        Prime = computePrime(maxE)
      
        # To store the count of pairs
        count = 0
      
        # To store the frequency of
        # element in the array arr[]
        freq = [0]*(maxE + 2)
      
        for i in range( n):
            freq[arr[i]] += 1
      
        # Sort before traversing the array
        arr.sort()
      
        # Traverse the array and find
        # the pairs with Twin Primes
        for i in range(n):
      
            # If current element is
            # Prime, then check for
            # (current element + 2)
            if (Prime[arr[i]]):
                if ((arr[i] + 2) <= (maxE) and freq[arr[i] + 2] > 0
                    and Prime[arr[i] + 2]):
                    count += 1
      
        # Return the count of pairs
        return count
      
    # Driver's code
    if __name__ == "__main__":
          
        arr = [ 2, 4, 3, 5, 7 ]
        n = len(arr)
      
        # Function call to find
        # Twin Primes pair
        print( countTwinPairs(arr, n))
          
    # This code is contributed by chitranayal
    

    C#

    // C# program to count Twin
    // Prime pairs in array
    using System;
    using System.Linq;
      
    class GFG{
        
    // To store check the prime
    // number
    static bool []Prime;
        
    // A utility function that find
    // the Prime Numbers till N
    static void computePrime(int N)
    {
        
        // Resize the Prime Number
        Prime = new bool[N + 1];
        for (int i = 0; i  <= N; i++){
            Prime[i] = true;    
        }
      
        Prime[0] = Prime[1] = false;
        
        // Loop till Math.Sqrt(N) to find
        // prime numbers and make their
        // multiple false in the bool
        // array Prime
        for (int i = 2; i * i <= N; i++) {
            if (Prime[i]) {
                for (int j = i * i; j < N; j += i) {
                    Prime[j] = false;
                }
            }
        }
    }
        
    // Function that returns the count
    // of Twin Prime Pairs
    static int countTwinPairs(int []arr, int n)
    {
        
        // Find the maximum element in
        // the given array []arr
        int maxE = arr.Max();
        
        // Function to calculate the
        // prime numbers till N
        computePrime(maxE);
        
        // To store the count of pairs
        int count = 0;
        
        // To store the frequency of
        // element in the array []arr
        int []freq = new int[maxE + 1];
        
        for (int i = 0; i < n; i++) {
            freq[arr[i]]++;
        }
        
        // Sort before traversing the array
        Array.Sort(arr);
        
        // Traverse the array and find
        // the pairs with Twin Primes
        for (int i = 0; i < n; i++) {
        
            // If current element is
            // Prime, then check for
            // (current element + 2)
            if (Prime[arr[i]]) {
                if (arr[i] + 2 < freq.Length && freq[arr[i] + 2] > 0
                    && Prime[arr[i] + 2]) {
                    count++;
                }
            }
        }
        
        // Return the count of pairs
        return count;
    }
        
    // Driver's code
    public static void Main(String[] args)
    {
        int []arr = { 2, 4, 3, 5, 7 };
        int n = arr.Length;
        
        // Function call to find
        // Twin Primes pair
        Console.Write(countTwinPairs(arr, n));
    }
    }
       
    // This code is contributed by PrinciRaj1992
    
    输出:
    2
    

    时间复杂度: O(N * sqrt(M)),其中N是给定数组中元素的数量,M是数组中最大的元素。
    辅助空间: O(N)