筛选法求素数
筛选法求素数
http://www.nowcoder.com/questionTerminal/06c3dcc303654ef4926654023eca1e5a
解题思路
- 埃托拉斯筛选法
- 快速求0的数量
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = 0; int[] primes = new int[105]; int[] st = new int[105]; Arrays.fill(st, 0); for(int i = 2; i <= n; i++){ if(st[i] == 0){ primes[k++] = i; for(int j = i+i; j <= n; j+=i){ st[j] = 1; } } } for(int i = 0; i < k; i++){ System.out.print(primes[i]+" "); } System.out.println(); System.out.println(n-k-1); } }
Java算法题解 文章被收录于专栏
Java算法题