素数对猜想(埃氏筛法)_System


这一题用数组存素数的时候用了埃氏筛法,关于埃氏筛法可以参考我的另一篇博客埃氏筛法。

import java.util.Scanner;

public class Main {
    public static boolean[] is_prime = new boolean[100001];
    public static int[] prime = new int[100001];

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        cin.close();
        int p = sieve(n);
        int sum = 0;
        if (p >= 2) {
            for (int i = 0; i < p - 1; ++i) {
                if (prime[i + 1] - prime[i] == 2) {
                    ++sum;
                }
            }
        }
        System.out.println(sum);
    }

    public static int sieve(int n) {
        is_prime[0] = is_prime[1] = false;
        for (int i = 2; i <= n; ++i) {
            is_prime[i] = true;
        }
        int p = 0;
        for (int i = 2; i <= n; ++i) {
            if (is_prime[i]) {
                prime[p++] = i;
                for (int j = 2 * i; j <= n; j += i) {
                    is_prime[j] = false;
                }
            }
        }
        return p;
    }
}


========================================Talk is cheap, show me the code=======================================