Definition of prime numbers: Prime numbers refer to natural numbers greater than 1 that have no other factors except 1 and itself.
Ehrlich sieve method: In simple terms, it is to traverse the entire array, set each number 2 times, 3 times ... to -1 (uncrossable), and then traverse the new array to quickly find the nth prime number.
And compare its method with the conventional method
code show as below:
import java.util.Scanner;
public class Sscs {
//素数测试(找到第n个素数)
//方法一:对一组数据中的每个数字进行鉴别是否为素数,找到对应的值
//方法二:埃氏筛法
static boolean sushu(int a)
{
for(int i=2;i<Math.sqrt(a);i++)//直接查询2-sqrt(a)加快速度
{
if(a%i==0)
return false;
}
return true;
}
static void fa1(int n,int m)//方法一的实现
{
int count=0;
for(int i=2;i<=m;i++)
{
if(sushu(i))
{
count++;
if(count==n)
System.out.println(i);
}
}
}
static void fa2(int n,int m)//方法二实现:埃氏筛法
{
int []a=new int[m];
for(int i=2;i<a.length;i++)//遍历每一位数据,将其倍数全部置为-1
{
if(a[i]==-1)
continue;
int k=2;
while(i*k<m)
{
a[i*k]=-1;
k++;
}
}
int count=0;
for(int i=2;i<a.length;i++)//遍历查找第n个素数
{
if(a[i]==0)
count++;
if(count==n)
{ System.out.println(i);
break;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner a=new Scanner(System.in);
int n=a.nextInt();//输入需要查询的第n个数
int b=2;
while(b/Math.log(b)<n)//查询第n个素数时需要准备多少的数组长度
{
b++;
}
long now1=System.currentTimeMillis();//记录方法一的初始时间
fa1(n,b);
System.out.println(System.currentTimeMillis()-now1+"ms");//输出方法一所需要的时间
long now2=System.currentTimeMillis();//记录方法一的初始时间
fa2(n,b);
System.out.println(System.currentTimeMillis()-now2+"ms");//输出方法二所需要的时间
}
}