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.
Input: n =10Output: [[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.
To find all pairs of primes (x, y) such that x + y = n and 1 <= x <= y <= n, we need to efficiently check for primes up to n. The Sieve of Eratosthenes is ideal for this. For each x from 2 to n//2, if both x and n-x are prime, (x, n-x) is a valid pair.
import java.util.*;
classSolution {
public List<List<Integer>>findPrimePairs(int n) {
boolean[] isPrime =newboolean[n+1];
Arrays.fill(isPrime, true);
isPrime[0]= 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;
}
}
List<List<Integer>> res =new ArrayList<>();
for (int x = 2; x <= n/2; ++x) {
int y = n - x;
if (isPrime[x]&& isPrime[y]) {
res.add(Arrays.asList(x, y));
}
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funfindPrimePairs(n: Int): List<List<Int>> {
val isPrime = BooleanArray(n + 1) { true }
isPrime[0] = false; isPrime[1] = falsefor (i in2..Math.sqrt(n.toDouble()).toInt()) {
if (isPrime[i]) {
for (j in i * i..n step i) isPrime[j] = false }
}
val res = mutableListOf<List<Int>>()
for (x in2..n/2) {
val y = n - x
if (isPrime[x] && isPrime[y]) res.add(listOf(x, y))
}
return res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from typing import List
deffindPrimePairs(n: int) -> List[List[int]]:
is_prime = [True] * (n+1)
is_prime[0:2] = [False, False]
for i in range(2, int(n**0.5)+1):
if is_prime[i]:
for j in range(i*i, n+1, i):
is_prime[j] =False res = []
for x in range(2, n//2+1):
y = n - x
if is_prime[x] and is_prime[y]:
res.append([x, y])
return res
fnfind_prime_pairs(n: i32) -> Vec<Vec<i32>> {
let n = n asusize;
letmut is_prime =vec![true; n+1];
is_prime[0] =false;
is_prime[1] =false;
for i in2..=((n asf64).sqrt() asusize) {
if is_prime[i] {
letmut j = i * i;
while j <= n {
is_prime[j] =false;
j += i;
}
}
}
letmut res =vec![];
for x in2..=n/2 {
let y = n - x;
if is_prime[x] && is_prime[y] {
res.push(vec![x asi32, y asi32]);
}
}
res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
exportfunctionfindPrimePairs(n: number):number[][] {
constisPrime= Array(n+1).fill(true);
isPrime[0] =isPrime[1] =false;
for (leti=2; i*i<=n; ++i) {
if (isPrime[i]) {
for (letj=i*i; j<=n; j+=i) isPrime[j] =false;
}
}
constres: number[][] = [];
for (letx=2; x<=n/2; ++x) {
consty=n-x;
if (isPrime[x] &&isPrime[y]) res.push([x, y]);
}
returnres;
}