埃拉托色尼筛选法--JAVA

package javaapplication3;

import java.util.*;

/**
 * @author ChenYeKe
 * 埃拉托色尼筛选法(the Sieve of Eratosthenes)简称埃氏筛法
 * 未优化
 */
public class JavaApplication3 {

    public static void main(String[] args) {
        /* TODO code application logic her 
    Scanner cin=new Scanner(System.in);
    int a;
    a=cin.nextInt();
    System.out.println(a);*/
        // int N=Integer.parseInt(args[0]);
        Scanner cin = new Scanner(System.in);
        int N;
        N = cin.nextInt();

        boolean[] a = new boolean[N];
        for (int i = 2; i < N; i++) {
            a[i] = true;
        }
        for (int i = 2; i < Math.sqrt(N); i++) {
            if (a[i] != false) {
                for (int j = i; j * i < N; j++) {
                    a[i * j] = false;
                }
            }
        }
        int cnt=0;
        for (int i = 2; i < N; i++) {
            if (a[i]) {
               cnt++;
                System.out.println(i);
            }
        }
               System.out.println(N+"以内的素数有"+cnt+"个");
    }
}

你可能感兴趣的:(自习)