使用 C++ 查找子数组中的素数个数
在本文中,我们将介绍查找子数组中素数个数的方法。我们有一个正数数组 arr[] 和 q 个查询,每个查询包含两个整数,表示我们的范围 {l, R},我们需要找到给定范围内的素数个数。以下是一个给定问题的示例:
Input : arr[] = {1, 2, 3, 4, 5, 6}, q = 1, L = 0, R = 3
Output : 2
In the given range the primes are {2, 3}.
Input : arr[] = {2, 3, 5, 8 ,12, 11}, q = 1, L = 0, R = 5
Output : 4
In the given range the primes are {2, 3, 5, 11}.查找解决方案的方法
在这种情况下,我们会想到两种方法:
暴力法
在这种方法中,我们可以获取范围并查找该范围内存在的素数个数。
示例
#include <bits/stdc++.h>
using namespace std;
bool isPrime(int N){
if (N <= 1)
return false;
if (N <= 3)
return true;
if(N % 2 == 0 || N % 3 == 0)
return false;
for (int i = 5; i * i <= N; i = i + 2){ // as even number can't be prime so we increment i by 2.
if (N % i == 0)
return false; // if N is divisible by any number then it is not prime.
}
return true;
}
int main(){
int N = 6; // size of array.
int arr[N] = {1, 2, 3, 4, 5, 6};
int Q = 1;
while(Q--){
int L = 0, R = 3;
int cnt = 0;
for(int i = L; i <= R; i++){
if(isPrime(arr[i]))
cnt++; // counter variable.
}
cout << cnt << "\n";
}
return 0;
}输出
2
但是,这种方法不是很好,因为这种方法的整体复杂度为 **O(Q*N*√N)**,这并不是很好。
高效方法
在这种方法中,我们将使用埃拉托色尼筛法创建一个布尔数组,该数组告诉我们元素是否为素数,然后遍历给定范围并在布尔数组中查找素数的总数。
示例
#include <bits/stdc++.h>
using namespace std;
vector<bool> sieveOfEratosthenes(int *arr, int n, int MAX){
vector<bool> p(n);
bool Prime[MAX + 1];
for(int i = 2; i < MAX; i++)
Prime[i] = true;
Prime[1] = false;
for (int p = 2; p * p <= MAX; p++) {
// If prime[p] is not changed, then
// it is a prime
if (Prime[p] == true) {
// Update all multiples of p
for (int i = p * 2; i <= MAX; i += p)
Prime[i] = false;
}
}
for(int i = 0; i < n; i++){
if(Prime[arr[i]])
p[i] = true;
else
p[i] = false;
}
return p;
}
int main(){
int n = 6;
int arr[n] = {1, 2, 3, 4, 5, 6};
int MAX = -1;
for(int i = 0; i < n; i++){
MAX = max(MAX, arr[i]);
}
vector<bool> isprime = sieveOfEratosthenes(arr, n, MAX); // boolean array.
int q = 1;
while(q--){
int L = 0, R = 3;
int cnt = 0; // count
for(int i = L; i <= R; i++){
if(isprime[i])
cnt++;
}
cout << cnt << "\n";
}
return 0;
}输出
2
上述代码的解释
这种方法比我们之前应用的暴力法快得多,因为现在的时空复杂度为 **O(Q*N)**,这比之前的复杂度好得多。
在这种方法中,我们预先计算元素并将其标记为素数或非素数;因此,这降低了我们的复杂度。最重要的是,我们还使用了埃拉托色尼筛法,这将帮助我们更快地找到素数。在这种方法中,我们通过使用素因数标记数字,以 **O(N*log(log(N)))** 的复杂度将所有数字标记为素数或非素数。
结论
在本文中,我们解决了一个问题,即使用埃拉托色尼筛法以 O(Q*N) 的时间复杂度查找子数组中的素数个数。我们还学习了此问题的 C++ 程序以及解决此问题的完整方法(普通和高效)。我们可以用其他语言(如 C、Java、Python 和其他语言)编写相同的程序。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP