@@ -207,7 +207,7 @@ To solve such a problem, we can use the idea of the Segmented sieve.
207
207
We pre-generate all prime numbers up to $\sqrt R$, and use those primes to mark all composite numbers in the segment $[L, R]$.
208
208
209
209
```cpp
210
- vector<char> segmentedSieve (long long L, long long R) {
210
+ vector<char> segmented_sieve (long long L, long long R) {
211
211
// generate all primes up to sqrt(R)
212
212
long long lim = sqrt(R);
213
213
vector<char> mark(lim + 1, false);
@@ -222,10 +222,12 @@ vector<char> segmentedSieve(long long L, long long R) {
222
222
223
223
vector<char> isPrime(R - L + 1, true);
224
224
for (long long i : primes)
225
- for (long long j = max(i * i , (L + i - 1) / i * i) ; j <= R; j += i)
225
+ for (long long j = max(i, (L + i - 1) / i) * i; j <= R; j += i)
226
226
isPrime[j - L] = false;
227
- if (L == 1)
228
- isPrime[0] = false;
227
+ if (L == 0)
228
+ isPrime[L] = false;
229
+ if (L <= 1)
230
+ isPrime[min(1 - L, R - L)] = false;
229
231
return isPrime;
230
232
}
231
233
```
@@ -234,14 +236,16 @@ Time complexity of this approach is $O((R - L + 1) \log \log (R) + \sqrt R \log
234
236
It's also possible that we don't pre-generate all prime numbers:
235
237
236
238
``` cpp
237
- vector<char > segmentedSieveNoPreGen (long long L, long long R) {
239
+ vector<char > segmented_sieve_no_pre_gen (long long L, long long R) {
238
240
vector<char > isPrime(R - L + 1, true);
239
241
long long lim = sqrt(R);
240
242
for (long long i = 2; i <= lim; ++i)
241
- for (long long j = max(i * i , (L + i - 1) / i * i) ; j <= R; j += i)
243
+ for (long long j = max(i, (L + i - 1) / i) * i; j <= R; j += i)
242
244
isPrime[ j - L] = false;
243
- if (L == 1)
244
- isPrime[ 0] = false;
245
+ if (L == 0)
246
+ isPrime[ L] = false;
247
+ if (L <= 1)
248
+ isPrime[ min(1 - L, R - L)] = false;
245
249
return isPrime;
246
250
}
247
251
```
@@ -258,6 +262,7 @@ However, this algorithm also has its own weaknesses.
258
262
259
263
* [Leetcode - Four Divisors](https://leetcode.com/problems/four-divisors/)
260
264
* [Leetcode - Count Primes](https://leetcode.com/problems/count-primes/)
265
+ * [Leetcode - Closest Prime Numbers in Range](https://leetcode.com/problems/closest-prime-numbers-in-range/)
261
266
* [SPOJ - Printing Some Primes](http://www.spoj.com/problems/TDPRIMES/)
262
267
* [SPOJ - A Conjecture of Paul Erdos](http://www.spoj.com/problems/HS08PAUL/)
263
268
* [SPOJ - Primal Fear](http://www.spoj.com/problems/VECTAR8/)
0 commit comments