生成两个给定数字之间的所有质数。任务是打印该范围内的质数。 Eratosthenes的筛子是查找所有小于n的素数(其中n小于1000万左右)的最有效方法之一。
例子:
Input : start = 50 end = 100
Output : 53 59 61 67 71 73 79 83 89 97
Input : start = 900 end = 1000
Output : 907 911 919 929 937 941 947 953 967 971 977 983 991 997
想法是使用Eratosthenes筛子作为子例程。首先,找到从0开始的质数,并将其存储在向量中。同样,找到从0到结束范围内的质数,并将其存储在另一个向量中。现在,将两个向量的集合差取为所需的答案。如果向量中有多余的零,请将其删除。
// C++ STL program to print all primes
// in a range using Sieve of Eratosthenes
#include
using namespace std;
typedef unsigned long long int ulli;
vector sieve(ulli n)
{
// Create a boolean vector "prime[0..n]" and
// initialize all entries it as true. A value
// in prime[i] will finally be false if i is
// Not a prime, else true.
vector prime(n+1,true);
prime[0] = false;
prime[1] = false;
int m = sqrt(n);
for (ulli p=2; p<=m; p++)
{
// If prime[p] is not changed, then it
// is a prime
if (prime[p])
{
// Update all multiples of p
for (ulli i=p*2; i<=n; i += p)
prime[i] = false;
}
}
// push all the primes into the vector ans
vector ans;
for (int i=0;i sieveRange(ulli start,ulli end)
{
// find primes from [0..start] range
vector s1 = sieve(start);
// find primes from [0..end] range
vector s2 = sieve(end);
vector ans(end-start);
// find set difference of two vectors and
// push result in vector ans
// O(2*(m+n)-1)
set_difference(s2.begin(), s2.end(), s1.begin(),
s2.end(), ans.begin());
// remove extra zeros if any. O(n)
vector::iterator itr =
remove_if(ans.begin(),ans.end(),isZero);
// resize it. // O(n)
ans.resize(itr-ans.begin());
return ans;
}
// Driver Program to test above function
int main(void)
{
ulli start = 50;
ulli end = 100;
vector ans = sieveRange(start,end);
for (auto i:ans)
cout<
输出:
53 59 61 67 71 73 79 83 89 97