线性筛选法求素数

import java.util.Scanner;

public class Main{
    
    public static int prime(int n) {
        
        if(n == 0)
            return -1;
        int[] a = new int[n + 1];
        int[] p = new int[n];
        int index = 0;
        for(int i = 2; i < n; i++) {
            
            if(a[i] == 0){
                
                p[index ++] = i;
                System.out.print(i + " ");
            }
                
            for(int j = 0; j < index && i * p[j] < n; j++) {
                
                a[i * p[j]] = 1;
                if(i % p[j] == 0)
                    break;
            }
        }
        return index;
    }
    public static void main(String[] args) {
        
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int count = prime(n);
        System.out.println(count);
    }
}

你可能感兴趣的:(线性筛选法求素数)