File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ vector<int> closestPrimes(int left, int right) {
4+ vector<bool> isPrime(right + 1, true);
5+ isPrime[0] = isPrime[1] = false;
6+ for (int i = 2; i * i <= right; i++) {
7+ if (isPrime[i]) {
8+ for (int j = i * i; j <= right; j += i) {
9+ isPrime[j] = false;
10+ }
11+ }
12+ }
13+ vector<int> primes;
14+ for (int i = left; i <= right; i++) {
15+ if (isPrime[i]) primes.push_back(i);
16+ }
17+ if (primes.size() < 2) return {-1, -1};
18+ vector<int> res(2);
19+ int minDiff = INT_MAX;
20+ for (int i = 1; i < primes.size(); i++) {
21+ int diff = primes[i] - primes[i - 1];
22+ if (diff < minDiff) {
23+ minDiff = diff;
24+ res[0] = primes[i - 1];
25+ res[1] = primes[i];
26+ }
27+ }
28+ return res;
29+ }
30+ };
You can’t perform that action at this time.
0 commit comments