Posted on

Description

Submission

class Solution {
    int generatePalindrome(int n) {
        string s = to_string(n);
        reverse_copy(s.begin(), s.end() - 1, back_inserter(s));
        return stoi(s);
    }

    bool isPrime(int n) {
        if(n == 1) return false;
        if(n % 2 == 0) return n == 2;
        for(int i = 3; i < sqrt(n) + 1; ++i) {
            if(n % i == 0) return false;
        }
        return true;
    }
public:
    int primePalindrome(int n) {
        vector<int> single {2, 3, 5, 7, 11};

        for(auto x: single) {
            if(n <= x) return x;
        }

        for(int i = sqrt(n) - 1; i < sqrt(2e8) + 1; ++i) {
            int x = generatePalindrome(i);

            if(x >= n) {
                if(isPrime(x)) return x;
            }
        }

        return -1;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *