初学素数筛选打表法

创建一个数组 从2开始找是素数数组当前下标为true 再把当前下标的倍数标为false 因为质数的倍数一定不是质数。打好表就可以用了

import java.util.Arrays;
import java.util.Scanner;

public class Main {

	@SuppressWarnings("resource")
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			int n = sc.nextInt();
			boolean arr[] = new boolean[n + 1];
			int arr1[] = new int[n + 1];
			Arrays.fill(arr, true);
			for (int i = 0; i < arr1.length; i++) {
				arr1[i]=i;
			}
			int sum = 0;
			for (int i = 2; i < arr1.length; i++) {
				if (arr[i] == true) {
					sum++;
					int flag = 0;
					for (int j = 2; j <= Math.sqrt(i); j++) {
						if (i % j == 0) {
							flag++;
							break;
						}
					}
					if (flag == 0) {

						for (int j = 2; j * i < arr1.length; j++) {
							arr[i * j] = false;
						}
					}

				}
			}
			System.out.println(sum);

		}

	}

}

点赞