【发布时间】:2020-10-05 11:30:21
【问题描述】:
我需要打印从 1 到 1,000,000 的所有素数,并打印从 4 到 10,000 的所有偶数以及两个相加的素数。
我有一个筛法,可以将数组中的所有非素数更改为 0(问题特别要求这样做),我需要使用 goldbach 方法来传递这个数组并显示所有偶数从 4 到 10,000 和两个总和为该数字的素数。
问题的 Goldbach 部分的重点是有效地打印数字,我很确定我的解决方案使用多项式时间搜索,而正确的解决方案是通过线性时间搜索完成的。关于如何优化它的任何线索?
import java.lang.Math;
public class sieveAndGoldbach {
public static void sieve(int[] a) {
int n = a.length;
a[0] = 0;
for (int i = 1; i <= Math.sqrt(n); i++) {
if (a[i] != 0) {
for (int j = a[i]*a[i]; j <= n; j+=a[i]) {
a[j-1] = 0;
}
}
}
}
public static void goldbach(int[] a) {
int max = 10000;
for (int i = 4; i <= max; i += 2) {
int count = 0;
for (int j = 0; j < i/2; j++) {
if (a[j] != 0) {
int difference = i-a[j];
for (int k = 0; k < max; k++) {
if (a[k] == difference && count == 0) {
System.out.println(i + " = " + a[j] + " + " + (difference));
count++;
}
}
}
}
}
}
public static void main(String[] args) {
//initialize and fill array from 1 to n
int n = 1000000; //initially one million GOLDBACH METHOD WILL NOT WORK FOR n < 10,000
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = i + 1;
}
//Call sieve method on array a, then print all primes, not the zeros
sieve(a);
for (int i = 0; i < n; i++) {
if (a[i] != 0) {
System.out.print(a[i]);
System.out.print(" ");
}
}
System.out.print("\n");
//Call goldbach method on array a
goldbach(a);
}
}
【问题讨论】:
标签: java arrays optimization