Skip to content

2761. Prime Pairs With Target Sum 👍

  • Time: $O(n\log(\log n))$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  vector<vector<int>> findPrimePairs(int n) {
    const vector<bool> isPrime = sieveEratosthenes(n + 1);
    vector<vector<int>> ans;

    for (int i = 2; i <= n / 2; ++i)
      if (isPrime[i] && isPrime[n - i])
        ans.push_back({i, n - i});

    return ans;
  }

 private:
  vector<bool> sieveEratosthenes(int n) {
    vector<bool> isPrime(n, true);
    isPrime[0] = false;
    isPrime[1] = false;
    for (int i = 2; i * i < n; ++i)
      if (isPrime[i])
        for (int j = i * i; j < n; j += i)
          isPrime[j] = false;
    return isPrime;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public List<List<Integer>> findPrimePairs(int n) {
    boolean[] isPrime = sieveEratosthenes(n + 1);
    List<List<Integer>> ans = new ArrayList<>();

    for (int i = 2; i <= n / 2; ++i)
      if (isPrime[i] && isPrime[n - i])
        ans.add(List.of(i, n - i));

    return ans;
  }

  private boolean[] sieveEratosthenes(int n) {
    boolean[] isPrime = new boolean[n];
    Arrays.fill(isPrime, true);
    isPrime[0] = false;
    isPrime[1] = false;
    for (int i = 2; i * i < n; ++i)
      if (isPrime[i])
        for (int j = i * i; j < n; j += i)
          isPrime[j] = false;
    return isPrime;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def findPrimePairs(self, n: int) -> list[list[int]]:
    isPrime = self._sieveEratosthenes(n + 1)
    return [[i, n - i] for i in range(2, n // 2 + 1)
            if isPrime[i] and isPrime[n - i]]

  def _sieveEratosthenes(self, n: int) -> list[bool]:
    isPrime = [True] * n
    isPrime[0] = False
    isPrime[1] = False
    for i in range(2, int(n**0.5) + 1):
      if isPrime[i]:
        for j in range(i * i, n, i):
          isPrime[j] = False
    return isPrime


j