Contents
Solution
The problem is seemingly unsolvable (iterating all prime-numbers between [ L , R ] [L, R] [L,R] where 2 ≤ L ≤ R ≤ 2 e 9 2 \leq L \leq R \leq 2e9 2≤L≤R≤2e9), however, it’s vital to real the problem-content carefully, there maybe a hint ( R − l ≤ 1 e 6 R - l \leq 1e6 R−l≤1e6) in a corner;
--
There is an important property (a common and useful Trick) for an integer
x
x
x:
.
If
x
x
x is not a Prime-Number, then
m
i
n
(
p
i
)
≤
x
min(p_i) \leq \sqrt{ x}
min(pi)≤x (in other words, there must exist a Prime-Factors
p
p
p of
x
x
x such that
p
∣
x
∧
p
∈
[
1
,
x
]
p | x \ \ \land \ \ p \in [1, \sqrt{x}]
p∣x ∧ p∈[1,x])
As a result, we can stand in the converse view-point, focusing on all Primes
p
=
[
1
,
1
e
6
]
p = [1, 1e6]
p=[1,1e6] instead of
x
x
x, then any Multiple of
p
p
p must be not a Prime-Number;
.
Note that, this method would only sieved all Non-Prime-Numbers
a
a
a which contains a Prime-Number, that is,
a
=
0
/
1
a = 0/1
a=0/1 would not be sieved although they are also Non-Primes;
Finding out these Prime-Numbers in the range [ l , r ] [l, r] [l,r] where 0 ≤ l ≤ r ≤ 1 e 12 ∧ ( r − l ) ≤ 1 e 6 0 \leq l \leq r \leq 1e12 \quad \land (r-l) \leq 1e6 0≤l≤r≤1e12∧(r−l)≤1e6; the algorithm is:
int l, r;
bool Is_prime[ r - l + 1] = true;
for( p : $(all Primes `<= \sqrt{r}`){ //< any Non-Prime in [l,r] must has a Prime which is `<= \sqrt{r}`;
for( a : [$(all number in [l,r])]_AND_[$([k*p]_AND_[k>=2] (the multiple of `p`))]){ //< @Location-1
//< `a` is a multiple of `p`, and also `a != p` (very important);
Is_prime[ a - l] = false;
}
}
//>< note that, only a Non-Prime which has a Prime-Factor (>=2) would be sieved (set `false`); in other words, although `0,1` are also Non-Primes, they would not be sieved (you need check them specially);
vector<> primes;
for( i : [l,r]){
if( (i >= 2) && Is_prime[ i]){ //< @Location-0
primes.push_back( i);
}
}
But when you applied, it is very fallible, let’s see some mistakes:
+
If int r
, then for( int i = l; i <= r; ++i)
would be an error, cuz r
would equals INT_MAX
;
+
@Location-0, the additional i >= 2
;
+
@Location-1,
a
a
a is not the multiple of
p
p
p in the range
[
l
,
r
]
[l,r]
[l,r], you must make sure
a
>
p
a > p
a>p;