Complete Prime Number Problem
Description
LeetCode Problem 3765.
You are given an integer num.
A number num is called a Complete Prime Number if every prefix and every suffix of num is prime.
Return true if num is a Complete Prime Number, otherwise return false.
Note:
- A prefix of a number is formed by the first
kdigits of the number. - A suffix of a number is formed by the last
kdigits of the number. - Single-digit numbers are considered Complete Prime Numbers only if they are prime.
Example 1:
Input: num = 23
Output: true
Explanation:
- Prefixes of num = 23 are 2 and 23, both are prime.
- Suffixes of num = 23 are 3 and 23, both are prime.
- All prefixes and suffixes are prime, so 23 is a Complete Prime Number and the answer is true.
Example 2:
Input: num = 39
Output: false
Explanation:
- Prefixes of num = 39 are 3 and 39. 3 is prime, but 39 is not prime.
- Suffixes of num = 39 are 9 and 39. Both 9 and 39 are not prime.
- At least one prefix or suffix is not prime, so 39 is not a Complete Prime Number and the answer is false.
Example 3:
Input: num = 7
Output: true
Explanation:
- 7 is prime, so all its prefixes and suffixes are prime and the answer is true.
Constraints:
1 <= num <= 10^9
Solution
Approach: Check Every Prefix and Suffix
First write a primality test: a number below 2 is not prime, and otherwise it is prime when no i with 2 <= i and i * i <= x divides it.
Convert num to a string and test all its prefixes by building the value digit by digit from the left (x = x * 10 + digit), then all its suffixes by building from the right (x = digit * p + x, with p growing by a factor of 10). If any prefix or suffix is not prime, return false; if all are prime, return true. There are at most 10 digits, so at most 20 primality tests, each taking at most about 31,623 steps.
Complexity: O(sqrt(n) log n) time, where n is the value of num, and O(log n) space.
from math import sqrt
class Solution:
def completePrime(self, num: int) -> bool:
def is_prime(x: int) -> bool:
if x < 2:
return False
return all(x % i for i in range(2, int(sqrt(x)) + 1))
s = str(num)
x = 0
for c in s:
x = x * 10 + int(c)
if not is_prime(x):
return False
x, p = 0, 1
for c in s[::-1]:
x = p * int(c) + x
p *= 10
if not is_prime(x):
return False
return True