Problem Description
Given an integer n, find all pairs of prime numbers [x, y] such that 1 <= x <= y <= n and x + y equals n. The returned list should be sorted in increasing order of x. If no such pairs exist, return an empty array.
Key Insights
- Use the Sieve of Eratosthenes to efficiently generate all prime numbers up to n.
- For each prime number x, compute y = n - x and check if y is also prime.
- Ensure that x <= y to avoid duplicate and reversed pairs.
- Given the constraints (n up to 10^6), the sieve method is optimal for prime generation.
Space and Time Complexity
Time Complexity: O(n log log n) due to the Sieve of Eratosthenes. Space Complexity: O(n) for storing the boolean sieve array.
Solution
The solution involves two main steps:
- Generate a boolean array using the Sieve of Eratosthenes to mark all prime numbers up to n.
- Iterate over the numbers from 2 to n. For each number x that is prime, check if its complement y (where y = n - x) is also prime and satisfies x <= y. Add valid pairs to the result.
This approach guarantees that each pair is unique and returned in sorted order by design. Edge cases, like when n is too small to form any prime pairs, are naturally handled by the algorithm.