📌  相关文章
📜  给定范围内的 K 个远距离素数对

📅  最后修改于: 2021-09-05 11:42:45             🧑  作者: Mango

给定两个整数L、R和一个整数K ,任务是打印给定范围内差为K 的所有素数对。

例子:

朴素方法:最简单的方法是生成与给定范围具有差异K 的所有可能对,并检查两个对元素是否都是素数。如果存在这样的一对,则打印该对。

时间复杂度: O(sqrt((N))*(R – L + 1) 2 ),其中 N 是[L, R]范围内的任何数字。
辅助空间: O(1)

高效的方法:为了优化上述方法,其思想是使用 Eratosthenes 筛法找到给定范围[L, R]内的所有素数,并将其存储在 unordered_map M 中。现在,遍历M中的每个值(比如val ),如果(val + K)也存在于映射M 中,则打印该对。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to generate prime numbers
// in the given range [L, R]
void findPrimeNos(int L, int R,
                  unordered_map& M)
{
    // Store all value in the range
    for (int i = L; i <= R; i++) {
        M[i]++;
    }
 
    // Erase 1 as its non-prime
    if (M.find(1) != M.end()) {
        M.erase(1);
    }
 
    // Perform Sieve of Eratosthenes
    for (int i = 2; i <= sqrt(R); i++) {
 
        int multiple = 2;
 
        while ((i * multiple) <= R) {
 
            // Find current multiple
            if (M.find(i * multiple)
                != M.end()) {
 
                // Erase as it is a
                // non-prime
                M.erase(i * multiple);
            }
 
            // Increment multiple
            multiple++;
        }
    }
}
 
// Function to print all the prime pairs
// in the given range that differs by K
void getPrimePairs(int L, int R, int K)
{
    unordered_map M;
 
    // Generate all prime number
    findPrimeNos(L, R, M);
 
    // Traverse the Map M
    for (auto& it : M) {
 
        // If it.first & (it.first + K)
        // is prime then print this pair
        if (M.find(it.first + K)
            != M.end()) {
            cout << "(" << it.first
                 << ", "
                 << it.first + K
                 << ") ";
        }
    }
}
 
// Driver Code
int main()
{
    // Given range
    int L = 1, R = 19;
 
    // Given K
    int K = 6;
 
    // Function Call
    getPrimePairs(L, R, K);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
 
class solution{
 
// Function to generate prime
// numbers in the given range [L, R]
static void findPrimeNos(int L, int R,
                         Map M,
                         int K)
{
  // Store all value in the range
  for (int i = L; i <= R; i++)
  {
    if(M.get(i) != null)
      M.put(i, M.get(i) + 1);
    else
      M.put(i, 1);
  }
 
  // Erase 1 as its
  // non-prime
  if (M.get(1) != null)
  {
    M.remove(1);
  }
 
  // Perform Sieve of
  // Eratosthenes
  for (int i = 2;
           i <= Math.sqrt(R); i++)
  {
    int multiple = 2;
     
    while ((i * multiple) <= R)
    {
      // Find current multiple
      if (M.get(i * multiple) != null)
      {
        // Erase as it is a
        // non-prime
        M.remove(i * multiple);
      }
 
      // Increment multiple
      multiple++;
    }
  }
 
  // Traverse the Map M
  for (Map.Entry entry :
       M.entrySet()) 
  {
    // If it.first & (it.first + K)
    // is prime then print this pair
 
    if (M.get(entry.getKey() + K) != null)
    {
      System.out.print("(" + entry.getKey() +
                       ", " + (entry.getKey() +
                       K) + ") ");
    }
  }
}
 
// Function to print all
// the prime pairs in the
// given range that differs by K
static void getPrimePairs(int L,
                          int R, int K)
{
  Map M = new HashMap(); 
 
  // Generate all prime number
  findPrimeNos(L, R, M, K);
}
 
// Driver Code
public static void main(String args[])
{
  // Given range
  int L = 1, R = 19;
 
  // Given K
  int K = 6;
 
  // Function Call
  getPrimePairs(L, R, K);
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Python3
# Python3 program for the above approach
from math import sqrt
 
# Function to generate prime numbers
# in the given range [L, R]
def findPrimeNos(L, R, M):
     
    # Store all value in the range
    for i in range(L, R + 1):
        M[i] = M.get(i, 0) + 1
 
    # Erase 1 as its non-prime
    if (1 in M):
        M.pop(1)
 
    # Perform Sieve of Eratosthenes
    for i in range(2, int(sqrt(R)) + 1, 1):
        multiple = 2
 
        while ((i * multiple) <= R):
             
            # Find current multiple
            if ((i * multiple) in M):
                 
                # Erase as it is a
                # non-prime
                M.pop(i * multiple)
 
            # Increment multiple
            multiple += 1
 
# Function to print all the prime pairs
# in the given range that differs by K
def getPrimePairs(L, R, K):
     
    M = {}
 
    # Generate all prime number
    findPrimeNos(L, R, M)
 
    # Traverse the Map M
    for key, values in M.items():
         
        # If it.first & (it.first + K)
        # is prime then print this pair
        if ((key + K) in M):
            print("(", key, ",",
                  key + K, ")", end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Given range
    L = 1
    R = 19
 
    # Given K
    K = 6
 
    # Function Call
    getPrimePairs(L, R, K)
 
# This code is contributed by bgangwar59


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class solution{
 
// Function to generate prime
// numbers in the given range [L, R]
static void findPrimeNos(int L, int R,
                         Dictionary M, int K)
{
  // Store all value in the range
  for (int i = L; i <= R; i++)
  {
      if(M.ContainsKey(i))
      M.Add(i, M[i] + 1);
    else
      M.Add(i, 1);
  }
 
  // Erase 1 as its
  // non-prime
  if (M[1] != 0)
  {
    M.Remove(1);
  }
 
  // Perform Sieve of
  // Eratosthenes
  for (int i = 2;
           i <= Math.Sqrt(R); i++)
  {
    int multiple = 2;
     
    while ((i * multiple) <= R)
    {
      // Find current multiple
      if (M.ContainsKey(i * multiple))
      {
        // Erase as it is a
        // non-prime
        M.Remove(i * multiple);
      }
 
      // Increment multiple
      multiple++;
    }
  }
 
  // Traverse the Map M
  foreach (KeyValuePair entry in  M) 
  {
    // If it.first & (it.first + K)
    // is prime then print this pair
 
    if (M.ContainsKey(entry.Key + K))
    {
      Console.Write("(" + entry.Key +
                    ", " + (entry.Key +
                    K) + ") ");
    }
  }
}
 
// Function to print all
// the prime pairs in the
// given range that differs by K
static void getPrimePairs(int L,
                          int R, int K)
{
  Dictionary M = new Dictionary(); 
   
  // Generate all prime number
  findPrimeNos(L, R, M, K);
}
 
// Driver Code
public static void Main(String []args)
{
  // Given range
  int L = 1, R = 19;
 
  // Given K
  int K = 6;
 
  // Function Call
  getPrimePairs(L, R, K);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出
(5, 11) (7, 13) (11, 17) (13, 19) 

时间复杂度: O(N*log*(log(N)) + sqrt(R – L)),其中 N = R – L + 1
辅助空间: O(N)