C ++程序实现分段筛以生成给定范围之间的质数
这是C++程序,用于实现分段筛分以在给定范围之间生成素数。分段筛首先使用简单筛来查找小于或等于√(n)的素数。该算法的思想是将范围[0...n-1]划分为不同的段,并一一计算所有段中的素数。
算法
Begin Create function to find all primes smaller than limit using simple sieve of eratosthenes. Finds all prime numbers in given range using segmented sieve A) Compute all primes smaller or equal to square root of high using simple sieve B) Count of elements in given range C) Declaring boolean only for [low, high] D) Find the minimum number in [low ... high] that is a multiple of prime[i] (divisible by prime[i]) E) Mark multiples of prime[i] in [low … high] F) Numbers which are not marked in range, are prime End
范例程式码
#include <bits/stdc++.h>
using namespace std;
void simpleSieve(int lmt, vector<int>& prime) {
bool mark[lmt + 1];
memset(mark, false, sizeof(mark));
for (int i = 2; i <= lmt; ++i) {
if (mark[i] == false) {
prime.push_back(i);
for (int j = i; j <= lmt; j += i)
mark[j] = true;
}
}
}
void PrimeInRange(int low, int high) {
int lmt = floor(sqrt(high)) + 1;
vector<int> prime;
simpleSieve(lmt, prime);
int n = high - low + 1;
bool mark[n + 1];
memset(mark, false, sizeof(mark));
for (int i = 0; i < prime.size(); i++) {
int lowLim = floor(low / prime[i]) * prime[i];
if (lowLim < low)
lowLim += prime[i];
for (int j = lowLim; j <= high; j += prime[i])
mark[j - low] = true;
}
for (int i = low; i <= high; i++)
if (!mark[i - low])
cout << i << " ";
}
int main() {
int low = 10, high = 50;
PrimeInRange(low, high);
return 0;
}输出结果
11 13 17 19 23 29 31 37 41 43 47
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短