Leetcode Problem 2523. Closest Prime Numbers in Range

2523. Closest Prime Numbers in Range

Leetcode Solutions

Sieve of Eratosthenes and Prime Pair Search

  1. Initialize a boolean array isPrime with right + 1 elements, all set to true except for indices 0 and 1.
  2. Use the Sieve of Eratosthenes to mark non-prime numbers in isPrime by iterating from 2 to sqrt(right) and marking multiples of each number as false.
  3. Iterate through the range from left to right, and for each prime number found, check if it forms a pair with the previous prime number with a smaller difference than the current minimum.
  4. If a new minimum pair is found, update the result with the new pair.
  5. After the loop, return the result if a pair was found, or [-1, -1] otherwise.
UML Thumbnail

Iterative Prime Checking and Pair Finding

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...