📜  计算其差也是素数的素数对

📅  最后修改于: 2021-10-26 05:13:26             🧑  作者: Mango

给定一个整数N ,任务是计算范围[1, N]内的素数对的数量,使得每对元素之间的差也是一个素数。

例子:

朴素的方法:解决这个问题的最简单的方法是生成范围[1, N] 中所有可能的元素对,对于每一对,检查元素和元素之间的差是否是素数数与否。如果发现为真,则增加计数。最后,打印计数。

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

高效的方法:为了优化上述方法,该想法基于以下观察:

请按照以下步骤解决问题:

  • 初始化一个变量,比如cntPairs来存储素数对的计数,这样每对元素之间的差异也是一个素数。
  • 初始化一个数组,比如sieve[]来检查[1, N]范围内的数字是否是素数。
  • 使用埃拉托色尼筛法找出[1, N]范围内的所有素数。
  • 迭代范围[2, N] ,对于给定范围内的每个元素,检查筛 [i]筛 [i – 2]是否为真。如果发现为真,则将 cntPairs的值增加2
  • 最后,打印cntPairs的值。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to find all prime
// numbers in the range [1, N]
vector SieveOfEratosthenes(
    int N)
{
   
    // isPrime[i]: Stores if i is
    // a prime number or not
    vector isPrime(N, true);
   
    isPrime[0] = false;
    isPrime[1] = false;
   
    // Calculate all prime numbers up to
    // Max using Sieve of Eratosthenes
    for (int p = 2; p * p <= N; p++) {
   
        // If P is a prime number
        if (isPrime[p]) {
   
            // Set all multiple of P
            // as non-prime
            for (int i = p * p; i <= N;
                 i += p) {
   
                // Update isPrime
                isPrime[i] = false;
            }
        }
    }
    return isPrime;
}
 
// Function to count pairs of
// prime numbers in the range [1, N]
// whose difference is prime
int cntPairsdiffOfPrimeisPrime(int N)
{
     
    // Function to count pairs of
    // prime numbers whose difference  
    // is also a prime number
    int cntPairs = 0;
     
     
    // isPrime[i]: Stores if i is
    // a prime number or not
    vector isPrime
          = SieveOfEratosthenes(N);
     
    // Iterate over the range [2, N]
    for (int i = 2; i <= N; i++) {
         
         
        // If i and i - 2 is
        // a prime number
        if (isPrime[i] &&
            isPrime[i - 2]) {
               
               
            // Update cntPairs
            cntPairs += 2;
        }
    }
    return cntPairs;
}
 
// Driver Code
int main()
{
    int N = 5;
    cout << cntPairsdiffOfPrimeisPrime(N);
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
// Function to find all prime
// numbers in the range [1, N]
public static boolean[] SieveOfEratosthenes(int N)
{
     
    // isPrime[i]: Stores if i is
    // a prime number or not
    boolean[] isPrime = new boolean[N + 1];
    Arrays.fill(isPrime, true);
 
    isPrime[0] = false;
    isPrime[1] = false;
 
    // Calculate all prime numbers up to
    // Max using Sieve of Eratosthenes
    for(int p = 2; p * p <= N; p++)
    {
         
        // If P is a prime number
        if (isPrime[p])
        {
             
            // Set all multiple of P
            // as non-prime
            for(int i = p * p; i <= N; i += p)
            {
                 
                // Update isPrime
                isPrime[i] = false;
            }
        }
    }
    return isPrime;
}
 
// Function to count pairs of
// prime numbers in the range [1, N]
// whose difference is prime
public static int cntPairsdiffOfPrimeisPrime(int N)
{
     
    // Function to count pairs of
    // prime numbers whose difference
    // is also a prime number
    int cntPairs = 0;
 
    // isPrime[i]: Stores if i is
    // a prime number or not
    boolean[] isPrime = SieveOfEratosthenes(N);
 
    // Iterate over the range [2, N]
    for(int i = 2; i <= N; i++)
    {
         
        // If i and i - 2 is
        // a prime number
        if (isPrime[i] && isPrime[i - 2])
        {
             
            // Update cntPairs
            cntPairs += 2;
        }
    }
    return cntPairs;
}
 
// Driver Code
public static void main(String args[])
{
    int N = 5;
     
    System.out.println(cntPairsdiffOfPrimeisPrime(N));
}
}
 
// This code is contributed by hemanth gadarla


Python3
# Python3 program to implement
# the above approach
from math import sqrt
 
# Function to find all prime
# numbers in the range [1, N]
def SieveOfEratosthenes(N):
     
    # isPrime[i]: Stores if i is
    # a prime number or not
    isPrime = [True for i in range(N + 1)]
   
    isPrime[0] = False
    isPrime[1] = False
   
    # Calculate all prime numbers up to
    # Max using Sieve of Eratosthenes
    for p in range(2, int(sqrt(N)) + 1, 1):
         
        # If P is a prime number
        if (isPrime[p]):
             
            # Set all multiple of P
            # as non-prime
            for i in range(p * p, N + 1, p):
                 
                # Update isPrime
                isPrime[i] = False
                 
    return isPrime
 
# Function to count pairs of
# prime numbers in the range [1, N]
# whose difference is prime
def cntPairsdiffOfPrimeisPrime(N):
     
    # Function to count pairs of
    # prime numbers whose difference  
    # is also a prime number
    cntPairs = 0
     
    # isPrime[i]: Stores if i is
    # a prime number or not
    isPrime = SieveOfEratosthenes(N)
     
    # Iterate over the range [2, N]
    for i in range(2, N + 1, 1):
         
        # If i and i - 2 is
        # a prime number
        if (isPrime[i] and isPrime[i - 2]):
             
            # Update cntPairs
            cntPairs += 2
 
    return cntPairs
 
# Driver Code
if __name__ == '__main__':
     
    N = 5
     
    print(cntPairsdiffOfPrimeisPrime(N))
 
# This code is contributed by ipg2016107


C#
// C# program to implement
// the above approach 
using System;
  
class GFG{
     
// Function to find all prime
// numbers in the range [1, N]
public static bool[] SieveOfEratosthenes(int N)
{
     
    // isPrime[i]: Stores if i is
    // a prime number or not
    bool[] isPrime = new bool[N + 1];
    for(int i = 0; i < N + 1; i++)
    {
        isPrime[i] = true;
    }
  
    isPrime[0] = false;
    isPrime[1] = false;
  
    // Calculate all prime numbers up to
    // Max using Sieve of Eratosthenes
    for(int p = 2; p * p <= N; p++)
    {
         
        // If P is a prime number
        if (isPrime[p])
        {
             
            // Set all multiple of P
            // as non-prime
            for(int i = p * p; i <= N; i += p)
            {
                 
                // Update isPrime
                isPrime[i] = false;
            }
        }
    }
    return isPrime;
}
  
// Function to count pairs of
// prime numbers in the range [1, N]
// whose difference is prime
public static int cntPairsdiffOfPrimeisPrime(int N)
{
     
    // Function to count pairs of
    // prime numbers whose difference
    // is also a prime number
    int cntPairs = 0;
  
    // isPrime[i]: Stores if i is
    // a prime number or not
    bool[] isPrime = SieveOfEratosthenes(N);
  
    // Iterate over the range [2, N]
    for(int i = 2; i <= N; i++)
    {
         
        // If i and i - 2 is
        // a prime number
        if (isPrime[i] && isPrime[i - 2])
        {
             
            // Update cntPairs
            cntPairs += 2;
        }
    }
    return cntPairs;
}
  
// Driver Code
public static void Main()
{
    int N = 5;
      
    Console.WriteLine(cntPairsdiffOfPrimeisPrime(N));
}
}
 
// This code is contributed by susmitakundugoaldanga


Javascript


输出:
2

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