[LeetCode] Prime Pairs With Target Sum

6916. Prime Pairs With Target Sum

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 and y 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<vector<int>> findPrimePairs(int n) {
vector<bool> sieve(n+1, true);
sieve[0] = sieve[1] = 0;
for(long long i = 2; i <= n; i++) {
if(!sieve[i]) continue;
for(long long j = i * i; j <= n; j += i) sieve[j] = false;
}
vector<vector<int>> res;
for(int i = 2; 2 * i <= n; i++) {
int j = n - i;
if(i > j) break;
if(!sieve[i] or !sieve[j]) continue;
res.push_back({i,j});
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/02/PS/LeetCode/prime-pairs-with-target-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.