两个数字之间的半素数

时间:2016-06-09 00:07:16

标签: java algorithm primes sieve-of-eratosthenes

我正在解决编码问题,我调整了一些现有的代码,以便能够计算出有多少半素数存在,包括一定数量。

然而,我被困在我想要计算两个数字之间的唯一半素数的部分,例如10和4,它将是4,6,9和10,即4.我的答案只是说10有4个半素数,4有1个半素数,所以它们之间的子素数是4-1 = 3 。这是我出错的地方。

代码在这里:

public class SemiPrimeRange {
    public static int[] solution(int N, int[] P, int[] Q) {
        int arrSize = P.length;
        int[] arr = new int[arrSize];

        for (int i = 0; i < arr.length; i++) {
            int n = NoSemiPrimes(Q[i]);
            int m = NoSemiPrimes(P[i]);
            arr[i] = n-m;
        }

        for (int i : arr) {
            System.out.println(i);
        }
        return arr;

    }

    public static int NoSemiPrimes(int large) {
        int n = 0;

        boolean[] primeTop = new boolean[large + 1];
        boolean[] semiprimeTop = new boolean[large + 1];
        for (int i = 2; i <= large; i++) {
            primeTop[i] = true;
        }

        for (int i = 2; i * i <= large; i++) {
            if (primeTop[i]) {
                for (int j = i; i * j <= large; j++) {
                    primeTop[i * j] = false;
                }
            }
        }

        int primes = 0;
        for (int i = 2; i <= large; i++) {
            if (primeTop[i])
                primes++;
        }

        for (int i = 0; i < large; i++) {
            semiprimeTop[i] = false;
        }

        for (int i = 0; i <= large; i++) {
            for (int j = i; j <= large; j++) {
                if (primeTop[j]&&primeTop[i]) {
                    if(i*j<=large){
                        semiprimeTop[j*i] = true;
                    }           
                }
            }
        }

        for (int i = 0; i < semiprimeTop.length; i++) {
            System.out.println(semiprimeTop[i]);
        }

        int semiprimes = 0;
        for (int i = 2; i <= large; i++) {
            if (semiprimeTop[i])
                semiprimes++;
        }

        System.out.println("The number of semiprimes <= " + large + " is " + semiprimes);
        return semiprimes;

    }

    public static void main(String[] args) {
        int[] P = { 1, 4, 16 };
        int[] Q = { 26, 10, 20 };
        int N = 26;
        solution(N, P, Q);
    }

1 个答案:

答案 0 :(得分:3)

如果您想要yxy&gt; x)之间的半素数,count(y) - count(x)count(a)a和1之间的半素数不是正确的公式,因为如果它是半素数,它将省略x。正确的公式是count(y) - count(x - 1)

另请注意,您的代码无效,因为它会在1和较小的数字之间计算两次。

方法签名应为

public static int NoSemiPrimes(int small, int large)

并更改循环

int semiprimes = 0;
for (int i = 2; i <= large; i++) {
    if (semiprimeTop[i])
        semiprimes++;
}

int semiprimes = 0;
for (int i = small; i <= large; i++) {
    if (semiprimeTop[i])
        semiprimes++;
}

直接计算所需范围内的半素数,而不是两次使用int NoSemiPrimes(int large)