筛法求素数Java

时间:2023-03-09 07:53:15
筛法求素数Java

输出:一个集合S,表示1~n以内所有的素数

import java.util.Scanner;

public class 筛法求素数 {
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int[] arr = new int[n];
for (int i = 2; i < n; i++) {
arr[i] = i;
}
for (int i = 2; i < n; i++) {
if (arr[i] != 0) {
int j, temp;
temp = arr[i];
for (j = 2 * temp; j < n; j = j + temp) {
arr[j] = 0;
}
System.out.print(arr[i] + " ");
}
}
}
}

用途:列举1~n内所有的素数