[translate by ChatGPT] It’s been a while since I worked on prime-related problems. At first, I thought I needed to store previously computed primes, but it turns out that wasn’t necessary.

This problem has many boundary conditions. When dealing with primes, I need to be especially careful about handling 1 and 2 correctly.

Also, when checking whether a number is prime, it’s enough to check up to sqrt(n). That’s much faster than checking up to n/2.

Code

class Solution {
public:
    vector<int> closestPrimes(int left, int right) {
        int maxDist = right - left + 1;
        vector<int> maxSol = {-1,-1};
        vector<bool> nonPrimeSet(1e6, false);
        int prev = -100000;
        if(left % 2 == 0 && left != 2) ++left;
        for(int i = left ; i <= right ; i=update(i)) {
            if(nonPrimeSet[i]) {
                continue;
            }
            if(checkPrime(i)) {
                int diff = i - prev;
                if(prev != -100000 && maxDist > diff) {
                    maxDist = diff;
                    maxSol = {prev, i};
                    if(diff <= 2){
                        return maxSol;
                    }
                }
                prev = i;
                int cnt = i;
                while(cnt < right) {
                    nonPrimeSet[cnt] = true;
                    cnt += i;
                }
            }
        }
        return maxSol;
    }
    inline int update(int i){
        if(i <= 2) return i+1;
        else return i+2; 
    }
    bool checkPrime(int n) {
        if(n == 1) {
            return false;
        }
        for(int i = 2; i*i <= n; ++i) {
            if (n % i == 0) {
               return false;
            }
        }
        return true;
    }
};