给定偶数(大于2),返回两个素数,其总和将等于给定数。如果有多个解可能,则返回按字典缩小的解。
以下是我对此问题的解决方案
import java.util.ArrayList;
import java.lang.Math;
public class Solution {
public ArrayList<Integer> primesum(int a) {
ArrayList<Integer> b = new ArrayList<>();
ArrayList<Integer> original = new ArrayList<>();
ArrayList<Integer> to_return = new ArrayList<>();
ArrayList<Integer> bas = new ArrayList<>();
for(int i =0;i<a;i++){
original.add(i);
}
for(int i =0;i<a+1;i++){
b.add(1); //Initally all elements are prime!!
}
b.set(0,0);b.set(1,0);
for(int i=2;i<Math.sqrt(a);i++){
if(b.get(i)== 1){
for(int j =2;i*j<=a;j++){
b.set(i*j,0);
}
}
}
for(int i=0;i<a;i++){
if(b.get(i)==1){
to_return.add(original.get(i));
}
}
int f = to_return.size();
for(int i =0;i<f;i++){
if(i==f-1){
break;
}
if(to_return.contains(a-to_return.get(i))){
bas.add(to_return.get(i));
bas.add(a-to_return.get(i));
break;
}
}
return bas;
}
public static void main(String[] args) {
Solution s= new Solution();
System.out.println(s.primesum(16777214));
}
}
所以当输入数字是16777183时,我遇到java.lang.OutOfMemoryError:Java堆空间,我无法解决它,有人可以帮助我,我是相对较新的java。
答案 0 :(得分:-1)
你的Arraylist原版完全没用,因为只包含从0到a的数字所以它可以直接替换为i
public class Solution {
public ArrayList<Integer> primesum(int a) {
ArrayList<Integer> b = new ArrayList<>();
//ArrayList<Integer> original = new ArrayList<>();
ArrayList<Integer> to_return = new ArrayList<>();
ArrayList<Integer> bas = new ArrayList<>();
// for (int i = 0; i < a; i++) {
// original.add(i);
// }
for (int i = 0; i < a + 1; i++) {
b.add(1); //Initally all elements are prime!!
}
b.set(0, 0);
b.set(1, 0);
for (int i = 2; i < Math.sqrt(a); i++) {
if (b.get(i) == 1) {
for (int j = 2; i * j <= a; j++) {
b.set(i * j, 0);
}
}
}
for (int i = 0; i < a; i++) {
if (b.get(i) == 1) {
to_return.add(i);
}
}
int f = to_return.size();
for (int i = 0; i < f; i++) {
if (i == f - 1) {
break;
}
if (to_return.contains(a - to_return.get(i))) {
bas.add(to_return.get(i));
bas.add(a - to_return.get(i));
break;
}
}
return bas;
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.primesum(16777214));
}
}
它给出:[31,16777183]