素数筛:
Vis[]数组记录是否为素数,初始状态为全是素数。从零开始,0和1不是素数,标记为false,然后一个循环,从2开始,首先判断是否为素数,是的话,用prime[]数组存起来,cnt记录素数的个数。再然后一个循环,遍历小于i的prime[j]素数,然后再记录标记数组vis【i*prime[j]】为false。当i%prime[j]==0,break;
为什么当i%prime[j]==0,break;呢?
因为: 1、当i是素数,那肯定遍历到自己本身才会结束
2、当i不是素数,遍历到i的最小的一个因子结束。 这保证了一个合数的(去除)false(在vis标记),只会在 最小素因子*(自己/最小素因子)= 自己 。比如12:2*6,3*4.必定循环到 i=6,prime[j]=2时,才把12去掉,因为4绝对不是素数,不会到3才结束。
合数=a*b=c*d,且a<c<d<b,必定其中有一些倍数转换,比如24 = 3*8->3*2*4->6*4,
12 = 2*6->2*2*3->4*3。所以说,d必定有一个小于c的因子数。
附上一题:
Gdufe_2018_Summer III (L)
Prime Number
Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.
Input
Input consists of several datasets. Each dataset has an integer n (1 ≤ n ≤ 999,999) in a line.
The number of datasets is less than or equal to 30.
Output
For each dataset, prints the number of prime numbers.
Sample Input
10 3 11
Output for the Sample Input
4 2 5
题解:求1到n素数的个数。时间复杂度O(n)
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
while(scan.hasNext()){
int max = scan.nextInt();
System.out.println(get(max));
}
}
private static int get(int max) {
// TODO Auto-generated method stub
int cnt = 0;
boolean[] vis = new boolean[max+1];
Arrays.fill(vis, true);
int[] prime = new int[max];
vis[0] = false;vis[1] = false; //不是素数
for(int i=2;i<=max;i++){
if(vis[i]){
prime[cnt] = i;
cnt++;
}
for(int j=0;j<cnt&&i*prime[j]<=max;j++){
vis[i*prime[j]] = false;
if(i%prime[j]==0)
break;
}
}
return cnt;
}
}