To efficiently check for primes up to n, use the Sieve of Eratosthenes. For each a from 2 to n/2, check if both a and n-a are prime. The first such pair is the lexicographically smallest.
classSolution {
public: vector<int> primePairSum(int n) {
vector<bool> isPrime(n+1, 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;
}
}
for (int a =2; a <= n/2; ++a) {
if (isPrime[a] && isPrime[n-a]) return {a, n-a};
}
return {};
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicint[]primePairSum(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;
}
}
for (int a = 2; a <= n/2; ++a) {
if (isPrime[a]&& isPrime[n-a]) returnnewint[]{a, n-a};
}
returnnewint[0];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defprime_pair_sum(self, n: int) -> list[int]:
is_prime = [True] * (n+1)
is_prime[0] = is_prime[1] =Falsefor 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] =Falsefor a in range(2, n//2+1):
if is_prime[a] and is_prime[n-a]:
return [a, n-a]
return []