Leetcode 866. Prime Palindrome
Given an integer n
, return the smallest prime palindrome greater than or equal to n
. An integer is prime
if it has exactly two divisors: 1 and itself. An integer is a palindrome
if it reads the same from the left and right.
Output: 101
Explanation: 101 is a prime number and also a palindrome.
1 <= n <= 10^8
[2, 2 * 10^8]
.n
or is the brute force approach acceptable in terms of the problem constraints?Let’s assume that the inputs will always be within the provided constraints, and we should handle large values efficiently.
n
and look for the next number that is both a palindrome and prime.#include <iostream>
#include <cmath>
// Check if a number is a palindrome
bool isPalindrome(int x) {
// Convert number to string
std::string s = std::to_string(x);
int left = 0, right = s.size() - 1;
// Check symmetrical characters
while (left < right) {
if (s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
// Check if a number is prime
bool isPrime(int x) {
if (x < 2) return false;
if (x == 2 || x == 3) return true;
if (x % 2 == 0 || x % 3 == 0) return false;
for (int i = 5; i * i <= x; i += 6) {
if (x % i == 0 || x % (i + 2) == 0) return false;
}
return true;
}
// Main function to find the smallest prime palindrome greater than or equal to n
int primePalindrome(int n) {
// To handle edge cases efficiently directly
if (1 <= n && n <= 2) return 2;
if (n == 3) return 3;
if (n == 4) return 5;
if (n == 5) return 5;
// Start searching from the next odd number if n is even
if (n % 2 == 0) n++;
while (true) {
if (isPalindrome(n) && isPrime(n)) return n;
n += 2; // Increment by 2 to stay in the range of odd numbers
if (n > 1e7 && n < 2e7) n = 1e8 + 1; // Skip direct leap for a valid range edge case
}
}
int main() {
int n;
std::cin >> n;
std::cout << primePalindrome(n) << std::endl;
return 0;
}
n
.This strategy ensures we balance simplicity and performance to solve the problem within the given constraints efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?