Skip to content

Commit bccadb8

Browse files
authored
Create (Contest 352) 2761. Prime Pairs With Target Sum.java
1 parent 4054d18 commit bccadb8

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*Leetcode (Contest 352) 2761. Prime Pairs With Target Sum
2+
3+
You are given an integer n. We say that two integers x and y form a prime number pair if:
4+
5+
· 1 <= x <= y <= n
6+
· x + y == n
7+
· x and y are prime numbers
8+
9+
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.
10+
11+
Note: A prime number is a natural number greater than 1 with only two factors, itself and 1.
12+
13+
Example 1:
14+
15+
Input: n = 10
16+
Output: [[3,7],[5,5]]
17+
Explanation: In this example, there are two prime pairs that satisfy the criteria.
18+
These pairs are [3,7] and [5,5], and we return them in the sorted order as described in the problem statement.
19+
20+
Example 2:
21+
22+
Input: n = 2
23+
Output: []
24+
Explanation: We can show that there is no prime number pair that gives a sum of 2, so we return an empty array.
25+
26+
27+
Constraints:
28+
1 <= n <= 10^6
29+
*/
30+
31+
class Solution {
32+
/*埃拉托斯特尼筛法(埃氏筛)是一种用于枚举质数的算法。
33+
它的基本思想是从2开始,将每个素数的倍数标记为非素数,直到遍历完所有小于给定上限的数。
34+
35+
质数:质数是大于 1 的自然数,并且只有两个因子,即它 本身 和 1 。
36+
*/
37+
38+
private final static int MAX = (int) 1e6;
39+
private final static HashSet<Integer> set = new HashSet<>(); //用来储存范围内的所有质数
40+
static{
41+
boolean[] isPrime = new boolean[MAX + 1];
42+
//2是质数,则将其后面2的倍数的数字删除,因为他们都是2的倍数,所以不可能是质数,对于3,则删除3的倍数,
43+
//==> 以此类推,后面无法删除的数字则是质数
44+
for(int i = 2; i <= MAX; i++){
45+
if(!isPrime[i]){
46+
set.add(i);// 把得到的质数 加入到Hashset中储存
47+
for(int j = i; j <= MAX / i; j++){
48+
isPrime[j * i] = true; //如果存在新的因数,则标记true
49+
}
50+
}
51+
}
52+
}
53+
54+
//对于一个数字i,若i为质数且n-i也为质数,则这两个数字为满足题目要求的一个质数对
55+
//那么只需要在n/2的一半范围内求解即可
56+
public List<List<Integer>> findPrimePairs(int n) {
57+
List<List<Integer>> res = new ArrayList<>();
58+
for(int i = 2; i <= n/2; i++){
59+
if(set.contains(i) && set.contains(n - i) && i <= n - i){
60+
res.add(Arrays.asList(i, n - i));
61+
}
62+
}
63+
return res;
64+
}
65+
}

0 commit comments

Comments
 (0)