16(June) Prime Pair with Target Sum
16. Prime Pair with Target Sum
The problem can be found at the following link: Question Link
Problem Description
Given a number ( n ), find out if ( n ) can be expressed as ( a + b ), where both ( a ) and ( b ) are prime numbers. If such a pair exists, return the values of ( a ) and ( b ). Otherwise, return ([-1, -1]) as an array of size 2.
Examples:
Input:
n = 10Output:
3 7Explanation: There are two possibilities: 3 + 7 and 5 + 5 are both prime pairs that sum to 10. We choose 3 and 7 because 3 < 5.
My Approach
Initialization:
Create a boolean array
isPrimeof size ( n+1 ) to mark the primality of numbers up to ( n ). Initialize all entries as true except for indices 0 and 1, which are false.
Sieve of Eratosthenes:
Use the Sieve of Eratosthenes algorithm to find all prime numbers up to ( n ). For each prime number ( i ), mark all its multiples as non-prime.
Find Prime Pair:
Iterate through the first half of the
isPrimearray. For each prime number ( i ), check if ( n - i ) is also prime. If such a pair ( (i, n-i) ) is found, return it.
Return Default:
If no prime pair is found, return ([-1, -1]).
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n*loglog(n)), as the Sieve of Eratosthenes runs in this time complexity.
Expected Auxiliary Space Complexity: O(n), as we use a boolean array of size ( n+1 ) to mark prime numbers.
Code
C++
Java
Python
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated