解题思路
这是一个区间素数统计问题。需要高效地判断一个数是否为素数,并统计区间内的素数个数。
关键点:
- 高效的素数判断方法
- 避免对每个数都进行完整的素数判断
- 处理大数据范围(可达1000000)
算法步骤:
- 使用埃氏筛法预处理素数表
- 统计区间 内的素数个数
代码
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
vector<bool> isPrime;
void sieve(int n) {
isPrime.resize(n + 1, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
}
public:
int countPrimes(int m, int n) {
sieve(n);
int count = 0;
for (int i = m; i <= n; i++) {
if (isPrime[i]) {
count++;
}
}
return count;
}
};
int main() {
int m, n;
cin >> m >> n;
Solution solution;
cout << solution.countPrimes(m, n) << endl;
return 0;
}
import java.util.*;
public class Main {
static class Solution {
private boolean[] isPrime;
private void sieve(int n) {
isPrime = new boolean[n + 1];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
}
public int countPrimes(int m, int n) {
sieve(n);
int count = 0;
for (int i = m; i <= n; i++) {
if (isPrime[i]) {
count++;
}
}
return count;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
Solution solution = new Solution();
System.out.println(solution.countPrimes(m, n));
sc.close();
}
}
class Solution:
def __init__(self):
self.is_prime = []
def sieve(self, n: int):
self.is_prime = [True] * (n + 1)
self.is_prime[0] = self.is_prime[1] = False
i = 2
while i * i <= n:
if self.is_prime[i]:
for j in range(i * i, n + 1, i):
self.is_prime[j] = False
i += 1
def count_primes(self, m: int, n: int) -> int:
self.sieve(n)
return sum(1 for i in range(m, n + 1) if self.is_prime[i])
# 读取输入
m, n = map(int, input().split())
solution = Solution()
print(solution.count_primes(m, n))
算法及复杂度
- 算法:埃氏筛法
- 时间复杂度:,其中 是上界
- 空间复杂度:,需要存储素数表