Skip to main content

Sum of Primes Between Number and Its Reverse - Solution & Explanation

MediumMathNumber Theory8 min read
Practice this problem

Problem Statement

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

Approach Overview

Problem Overview: You are given an integer n. Reverse its digits to get another number rev. The task is to compute the sum of all prime numbers in the range between min(n, rev) and max(n, rev). The main challenge is efficiently identifying primes across that range.

Approach 1: Brute Force Primality Check (O(k * sqrt(k)) time, O(1) space)

Compute the reversed value of n, then determine the interval [L, R] where L = min(n, rev) and R = max(n, rev). Iterate through every number in this range and run a primality test for each value. A typical check tries dividing the number by all integers from 2 to sqrt(x). If no divisor is found, add it to the running sum. This method is straightforward and works well when the interval is small, but repeated square‑root checks make it slow for larger ranges.

Approach 2: Precompute Using Sieve of Eratosthenes (O(R log log R) time, O(R) space)

Instead of checking each number independently, generate all primes up to R using the Sieve of Eratosthenes. Create a boolean array where each index represents whether the number is prime. Start from 2, mark multiples as composite, and continue until sqrt(R). Once the sieve is built, iterate from L to R and sum values whose sieve entry is still marked prime. This avoids repeated factor checks and dramatically improves performance when the range is large. The sieve approach is a classic technique from number theory and math problems involving repeated prime queries.

Approach 3: Segmented Sieve for Large Ranges (O((R-L+1) log log R) time, O(R-L+1) space)

If R can be extremely large but the interval size (R-L) is manageable, a segmented sieve becomes more memory efficient. First compute primes up to sqrt(R). Then create a local boolean array representing only the interval [L, R]. Use the previously computed primes to mark multiples within this segment. Remaining unmarked numbers are prime and can be summed directly. This method avoids allocating a full sieve up to R and is commonly used in competitive programming when dealing with big numeric ranges.

Recommended for interviews: The Sieve of Eratosthenes approach is typically the expected solution. Starting with the brute force method shows you understand primality testing, but moving to the sieve demonstrates stronger algorithmic thinking and familiarity with efficient prime generation techniques. It reduces repeated work and keeps the runtime near linear relative to the range size.

Solution

We note that the reversed number r of n will not exceed 1000, so we can precompute all prime numbers up to 1000.

Next, we compute low = min(n, r) and high = max(n, r), then iterate through all integers in the range [low, high]. If an integer is prime, we add it to the answer.

The time complexity is O(n), and the space complexity is O(M), where M is the upper bound used for prime precomputation, which is 1000 here.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Primality CheckO(k * sqrt(k))O(1)Small ranges where direct prime checks are cheap
Sieve of EratosthenesO(R log log R)O(R)General case when R is moderate and multiple primes must be checked
Segmented SieveO((R-L+1) log log R)O(R-L+1)Very large upper bounds where allocating a full sieve up to R is impractical

Video Solution

weekly contest 500 | leetcode 3917 | leetcode 3918 | leetcode 3919 | leetcode 3920 | Easy solutionsCode With Vick567 views views

Watch 7 more video solutions →

Frequently Asked Questions

Is Sum of Primes Between Number and Its Reverse easy or hard?
The problem is generally classified as Medium because it combines two ideas: reversing an integer and efficiently computing primes in a numeric range. Developers familiar with sieve techniques can implement the optimal solution quickly.
Sum of Primes Between Number and Its Reverse Python/Java solution
Both Python and Java implementations typically compute the reversed integer, run a Sieve of Eratosthenes up to the maximum value, and iterate through the interval to accumulate primes. The core logic is identical across languages: sieve construction followed by a linear scan.
How to solve Sum of Primes Between Number and Its Reverse in O(n)?
A near‑linear solution uses the Sieve of Eratosthenes. Build a prime sieve up to the larger value between the number and its reverse, which takes O(n log log n). Then iterate through the required range and accumulate primes using constant‑time lookups from the sieve array.
What is the best approach for Sum of Primes Between Number and Its Reverse?
The Sieve of Eratosthenes is the most practical solution. Compute the reversed value of the number, determine the range [L, R], generate primes up to R using a sieve, then sum primes within the interval. This avoids repeated primality checks and runs in O(R log log R) time.
Is Sum of Primes Between Number and Its Reverse asked at Google/Amazon/Meta?
Variants of prime range queries and number reversal problems appear in interviews at large tech companies. While the exact problem title may vary, companies like Amazon and Google frequently test number theory basics such as primality testing and sieve-based optimizations.
What data structure is used in Sum of Primes Between Number and Its Reverse?
The optimal approach uses a boolean array (or bitset) to represent a sieve of primes. Each index indicates whether the number is prime, enabling constant-time checks when summing primes within the computed range.
What is the time complexity of Sum of Primes Between Number and Its Reverse?
The brute force approach that checks primality for each number runs in about O(k * sqrt(k)), where k is the size of the interval. The optimized sieve solution runs in O(R log log R) time with O(R) space, which is significantly faster for larger ranges.

Ready to solve this problem?

Practice Sum of Primes Between Number and Its Reverse with our built-in code editor and test cases.

Practice on FleetCode