📌  相关文章
📜  计算给定范围内的素数为素数的数

📅  最后修改于: 2021-05-06 19:19:25             🧑  作者: Mango

给定大小为N * 2的二维数组Q [] [] ,其形式为{L,R} 。对于每个查询,任务是打印范围为[L,R]的数量计数,其质数因子等于质数。

例子:

天真的方法:解决此问题的最简单方法是遍历[L,R]范围内的所有数字,并针对每个数字检查该数字的质数是否为质数。如果确定为真,则将计数器1 。遍历后,为每个查询打印计数器的值。

时间复杂度: O(| Q | *(max(arr [i] [1] – arr [i] [0] + 1))* sqrt(max(arr [i] [1])))
辅助空间: O(1)

高效的方法:为了优化上述方法,我们的想法是使用Eratosthenes的Sieve预先计算[L i ,R i ]范围内每个数的最小素因数。请按照以下步骤解决问题:

  • 使用Eratosthenes筛网生成并存储每个元素的最小素因数。
  • 使用筛子查找[L i ,R i ]范围内每个数字的质因子数。
  • 对于每个数字,检查质数因子的总数是否为质数。如果发现为真,则增加计数器。
  • 创建一个前缀求和数组,例如sum [],其中sum [i]将存储范围为[0,i]的素数为素数的元素之和。
  • 最后,对于每个查询,输出值sum [arr [i] [1]] – sum [arr [i] [0] – 1]

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
#define MAX 1001
 
// Function to find the smallest prime factor
// of all the numbers in range [0, MAX]
vector sieve()
{
 
    // Stores smallest prime factor of all
    // the numbers in the range [0, MAX]
    vector spf(MAX);
 
    // No smallest prime factor of
    // 0 and 1 exists
    spf[0] = spf[1] = -1;
 
    // Traverse all the numbers
    // in the range [1, MAX]
    for (int i = 2; i < MAX; i++) {
 
        // Update spf[i]
        spf[i] = i;
    }
 
    // Update all the numbers whose
    // smallest prime factor is 2
    for (int i = 4; i < MAX; i = i + 2) {
        spf[i] = 2;
    }
 
    // Traverse all the numbers in
    // the range [1, sqrt(MAX)]
    for (int i = 3; i * i < MAX; i++) {
 
        // Check if i is a prime number
        if (spf[i] == i) {
 
            // Update all the numbers whose
            // smallest prime factor is i
            for (int j = i * i; j < MAX;
                 j = j + i) {
 
                // Check if j is
                // a prime number
                if (spf[j] == j) {
                    spf[j] = i;
                }
            }
        }
    }
    return spf;
}
 
// Function to find count of
// prime factor of num
int countFactors(vector& spf, int num)
{
    // Stores count of
    // prime factor of num
    int count = 0;
 
    // Calculate count of
    // prime factor
    while (num > 1) {
 
        // Update count
        count++;
 
        // Update num
        num = num / spf[num];
    }
    return count;
}
 
// Function to precalculate the count of
// numbers in the range [0, i] whose count
// of prime factors is a prime number
vector precalculateSum(vector& spf)
{
 
    // Stores the sum of all the numbers
    // in the range[0, i] count of
    // prime factor is a prime number
    vector sum(MAX);
 
    // Update sum[0]
    sum[0] = 0;
 
    // Traverse all the numbers in
    // the range [1, MAX]
    for (int i = 1; i < MAX; i++) {
 
        // Stores count of prime factor of i
        int prime_factor
            = countFactors(spf, i);
 
        // If count of prime factor is
        // a prime number
        if (spf[prime_factor] == prime_factor) {
 
            // Update sum[i]
            sum[i] = sum[i - 1] + 1;
        }
        else {
 
            // Update sum[i]
            sum[i] = sum[i - 1];
        }
    }
    return sum;
}
 
// Driver Code
int main()
{
    // Stores smallest prime factor of all
    // the numbers in the range [0, MAX]
    vector spf = sieve();
 
    // Stores the sum of all the numbers
    // in the range[0, i] count of
    // prime factor is a prime number
    vector sum = precalculateSum(spf);
 
    int Q[][2] = { { 4, 8 }, { 30, 32 } };
 
    // int N = sizeof(Q) / sizeof(Q[0]);
    for (int i = 0; i < 2; i++) {
        cout << (sum[Q[i][1]] - sum[Q[i][0] - 1])
             << " ";
    }
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
public static int MAX = 1001;
 
// Function to find the smallest prime factor
// of all the numbers in range [0, MAX]
public static int[] sieve()
{
     
    // Stores smallest prime factor of all
    // the numbers in the range [0, MAX]
    int spf[] = new int[MAX];
   
    // No smallest prime factor of
    // 0 and 1 exists
    spf[0] = spf[1] = -1;
   
    // Traverse all the numbers
    // in the range [1, MAX]
    for(int i = 2; i < MAX; i++)
    {
         
        // Update spf[i]
        spf[i] = i;
    }
   
    // Update all the numbers whose
    // smallest prime factor is 2
    for(int i = 4; i < MAX; i = i + 2)
    {
        spf[i] = 2;
    }
   
    // Traverse all the numbers in
    // the range [1, sqrt(MAX)]
    for(int i = 3; i * i < MAX; i++)
    {
         
        // Check if i is a prime number
        if (spf[i] == i)
        {
             
            // Update all the numbers whose
            // smallest prime factor is i
            for(int j = i * i; j < MAX; j = j + i)
            {
                 
                // Check if j is
                // a prime number
                if (spf[j] == j)
                {
                    spf[j] = i;
                }
            }
        }
    }
    return spf;
}
   
// Function to find count of
// prime factor of num
public static int countFactors(int spf[], int num)
{
     
    // Stores count of
    // prime factor of num
    int count = 0;
   
    // Calculate count of
    // prime factor
    while (num > 1)
    {
         
        // Update count
        count++;
   
        // Update num
        num = num / spf[num];
    }
    return count;
}
   
// Function to precalculate the count of
// numbers in the range [0, i] whose count
// of prime factors is a prime number
public static int[] precalculateSum(int spf[])
{
     
    // Stores the sum of all the numbers
    // in the range[0, i] count of
    // prime factor is a prime number
    int sum[] = new int[MAX];
   
    // Update sum[0]
    sum[0] = 0;
   
    // Traverse all the numbers in
    // the range [1, MAX]
    for(int i = 1; i < MAX; i++)
    {
         
        // Stores count of prime factor of i
        int prime_factor = countFactors(spf, i);
   
        // If count of prime factor is
        // a prime number
        if (spf[prime_factor] == prime_factor)
        {
             
            // Update sum[i]
            sum[i] = sum[i - 1] + 1;
        }
        else
        {
             
            // Update sum[i]
            sum[i] = sum[i - 1];
        }
    }
    return sum;
}  
 
// Driver code
public static void main(String[] args)
{
     
    // Stores smallest prime factor of all
    // the numbers in the range [0, MAX]
    int spf[] = sieve();
   
    // Stores the sum of all the numbers
    // in the range[0, i] count of
    // prime factor is a prime number
    int sum[] = precalculateSum(spf);
   
    int Q[][] = { { 4, 8 }, { 30, 32 } };
   
    // int N = sizeof(Q) / sizeof(Q[0]);
    for(int i = 0; i < 2; i++)
    {
        System.out.print((sum[Q[i][1]] -
                          sum[Q[i][0] - 1]) + " ");
    }
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program to implement
# the above approach
MAX = 1001
 
# Function to find the smallest
# prime factor of all the numbers
# in range [0, MAX]
def sieve():
     
    # Stores smallest prime factor of all
    # the numbers in the range [0, MAX]
    global MAX
    spf = [0] * MAX
     
    # No smallest prime factor of
    # 0 and 1 exists
    spf[0] = spf[1] = -1
     
    # Traverse all the numbers
    # in the range [1, MAX]
    for i in range(2, MAX):
         
        # Update spf[i]
        spf[i] = i
 
    # Update all the numbers whose
    # smallest prime factor is 2
    for i in range(4, MAX, 2):
        spf[i] = 2
 
    # Traverse all the numbers in
    # the range [1, sqrt(MAX)]
    for i in range(3, MAX):
 
        # Check if i is a prime number
        if (spf[i] == i):
 
            # Update all the numbers whose
            # smallest prime factor is i
            for j in range(i * i, MAX):
                 
                # Check if j is
                # a prime number
                if (spf[j] == j):
                    spf[j] = i
 
    return spf
 
# Function to find count of
# prime factor of num
def countFactors(spf, num):
     
    # Stores count of
    # prime factor of num
    count = 0
 
    # Calculate count of
    # prime factor
    while (num > 1):
         
        # Update count
        count += 1
 
        # Update num
        num = num // spf[num]
 
    return count
 
# Function to precalculate the count of
# numbers in the range [0, i] whose count
# of prime factors is a prime number
def precalculateSum(spf):
     
    # Stores the sum of all the numbers
    # in the range[0, i] count of
    # prime factor is a prime number
    sum = [0] * MAX
 
    # Traverse all the numbers in
    # the range [1, MAX]
    for i in range(1, MAX):
         
        # Stores count of prime factor of i
        prime_factor = countFactors(spf, i)
 
        # If count of prime factor is
        # a prime number
        if (spf[prime_factor] == prime_factor):
 
            # Update sum[i]
            sum[i] = sum[i - 1] + 1
        else:
 
            # Update sum[i]
            sum[i] = sum[i - 1]
             
    return sum
 
# Driver code
if __name__ == '__main__':
 
    # Stores smallest prime factor of all
    # the numbers in the range [0, MAX]
    spf = sieve()
 
    # Stores the sum of all the numbers
    # in the range[0, i] count of
    # prime factor is a prime number
    sum = precalculateSum(spf)
 
    Q = [ [ 4, 8 ], [ 30, 32 ] ]
    sum[Q[0][1]] += 1
     
    # N = sizeof(Q) / sizeof(Q[0]);
    for i in range(0, 2):
        print((sum[Q[i][1]] -
               sum[Q[i][0]]), end = " ")
 
# This code is contributed by Princi Singh


C#
// C# program to implement
// the above approach
using System;
class GFG{
     
public static int MAX = 1001;
 
// Function to find the smallest
// prime factor of all the numbers
// in range [0, MAX]
public static int[] sieve()
{    
  // Stores smallest prime factor
  // of all the numbers in the
  // range [0, MAX]
  int []spf = new int[MAX];
 
  // No smallest prime factor
  // of 0 and 1 exists
  spf[0] = spf[1] = -1;
 
  // Traverse all the numbers
  // in the range [1, MAX]
  for(int i = 2; i < MAX; i++)
  {
    // Update spf[i]
    spf[i] = i;
  }
 
  // Update all the numbers whose
  // smallest prime factor is 2
  for(int i = 4; i < MAX; i = i + 2)
  {
    spf[i] = 2;
  }
 
  // Traverse all the numbers in
  // the range [1, sqrt(MAX)]
  for(int i = 3; i * i < MAX; i++)
  {
    // Check if i is a prime number
    if (spf[i] == i)
    {
      // Update all the numbers
      // whose smallest prime
      // factor is i
      for(int j = i * i;
              j < MAX; j = j + i)
      {
        // Check if j is
        // a prime number
        if (spf[j] == j)
        {
          spf[j] = i;
        }
      }
    }
  }
  return spf;
}
   
// Function to find count of
// prime factor of num
public static int countFactors(int []spf,
                               int num)
{    
  // Stores count of
  // prime factor of num
  int count = 0;
 
  // Calculate count of
  // prime factor
  while (num > 1)
  {
    // Update count
    count++;
 
    // Update num
    num = num / spf[num];
  }
  return count;
}
   
// Function to precalculate the count of
// numbers in the range [0, i] whose count
// of prime factors is a prime number
public static int[] precalculateSum(int []spf)
{    
  // Stores the sum of all the numbers
  // in the range[0, i] count of
  // prime factor is a prime number
  int []sum = new int[MAX];
 
  // Update sum[0]
  sum[0] = 0;
 
  // Traverse all the numbers in
  // the range [1, MAX]
  for(int i = 1; i < MAX; i++)
  {
 
    // Stores count of prime factor of i
    int prime_factor = countFactors(spf, i);
 
    // If count of prime factor is
    // a prime number
    if (spf[prime_factor] == prime_factor)
    {
 
      // Update sum[i]
      sum[i] = sum[i - 1] + 1;
    }
    else
    {
 
      // Update sum[i]
      sum[i] = sum[i - 1];
    }
  }
  return sum;
}  
 
// Driver code
public static void Main(String[] args)
{
  // Stores smallest prime factor
  // of all the numbers in the
  // range [0, MAX]
  int []spf = sieve();
 
  // Stores the sum of all the
  // numbers in the range[0, i]
  // count of prime factor is a
  // prime number
  int []sum = precalculateSum(spf);
 
  int [,]Q = {{4, 8}, {30, 32}};
 
  // int N = sizeof(Q) / sizeof(Q[0]);
  for(int i = 0; i < 2; i++)
  {
    Console.Write((sum[Q[i, 1]] -
                   sum[Q[i, 0] - 1]) +
                   " ");
  }
}
}
 
// This code is contributed by shikhasingrajput


输出:
3 2








时间复杂度: O(| Q | +(MAX * log(log(log(MAX))))
辅助空间: O(MAX)