Sum of Primes Between Number and Its Reverse Problem
#3918
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3918.
You are given an integer n.
Let r be the integer formed by reversing the digits of n.
Return the sum of all prime numbers between min(n, r) and max(n, r), inclusive.
Example 1:
Input: n = 13
Output: 132
Explanation:
- The reverse of 13 is 31. Thus, the range is [13, 31].
- The prime numbers in this range are 13, 17, 19, 23, 29, and 31.
- The sum of these prime numbers is 13 + 17 + 19 + 23 + 29 + 31 = 132.
Example 2:
Input: n = 10
Output: 17
Explanation:
- The reverse of 10 is 1. Thus, the range is [1, 10].
- The prime numbers in this range are 2, 3, 5, and 7.
- The sum of these prime numbers is 2 + 3 + 5 + 7 = 17.
Example 3:
Input: n = 8
Output: 0
Explanation:
- The reverse of 8 is 8. Thus, the range is [8, 8].
- There are no prime numbers in this range, so the sum is 0.
Constraints:
1 <= n <= 1000
Solution
Approach: Precompute Primes
The reverse of n is at most 999 when n <= 1000 (the reverse of 1000 is 1), so every number we may need is at most 1000. Sieve all primes up to 1000 once.
Reverse the digits of n to get r, take low = min(n, r) and high = max(n, r), and add up every prime in [low, high].
Complexity: time O(n) per call and space O(M), where M = 1000 is the sieve size.
limit = 1000
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(limit**0.5) + 1):
if is_prime[i]:
for j in range(i * i, limit + 1, i):
is_prime[j] = False
class Solution:
def sumOfPrimesInRange(self, n: int) -> int:
r = int(str(n)[::-1])
low = min(n, r)
high = max(n, r)
return sum(x for x in range(low, high + 1) if is_prime[x])