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 = 10

Output:

3 7

Explanation: 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

  1. Initialization:

  • Create a boolean array isPrime of 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.

  1. 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.

  1. Find Prime Pair:

  • Iterate through the first half of the isPrime array. For each prime number ( i ), check if ( n - i ) is also prime. If such a pair ( (i, n-i) ) is found, return it.

  1. 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