Problem
You are given an integer n
. We say that two integers x
and y
form a prime number pair if:
1 <= x <= y <= n
x + y == n
x
andy
are prime numbers
Return the 2D sorted list of prime number pairs [xi, yi]
. The list should be sorted in increasing order of xi
. If there are no prime number pairs at all, return an empty array.
Note: A prime number is a natural number greater than 1
with only two factors, itself and 1
.
Example 1:
Input: n = 10
Output: [[3,7],[5,5]]
Explanation: In this example, there are two prime pairs that satisfy the criteria.
These pairs are [3,7] and [5,5], and we return them in the sorted order as described in the problem statement.
Example 2:
Input: n = 2
Output: []
Explanation: We can show that there is no prime number pair that gives a sum of 2, so we return an empty array.
Constraints:
1 <= n <= 106
Solution (Java)
class Solution {
public List<List<Integer>> findPrimePairs(int n) {
List<List<Integer>> ans=new ArrayList<>();
boolean[]primes=sieveOfEratosthenes(n);
int[]vis=new int[n+1];
for(int i=1;i<=n;i++)
{
if((n-i)<=n && (n-i)>0 && primes[i] && primes[n-i] && vis[i]!=1 && vis[n-i]!=1)
{
ans.add(new ArrayList<>(Arrays.asList(i,n-i)));
vis[i]=1;
vis[n-i]=1;
}
}
Collections.sort(ans, (a, b) -> Integer.compare(a.get(0),b.get(0)));
return ans;
}
public static boolean[] sieveOfEratosthenes(int n)
{
boolean[] primes = new boolean[n + 1];
Arrays.fill(primes, true);
primes[0] = primes[1] = false;
for (int p = 2;p <= n; p++) {
if (primes[p] && (long)p*p<=n) {
for (int i = p * p; i <= n; i += p) {
primes[i] = false;
}
}
}
return primes;
}
}
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).