第六章 数学问题 ----------6.13 素数的筛法(第十万零二个素数)

素数定理:

       给出从整数中抽到素数的概率。从不大于n的自然数随机选一个,它是素数的概率大约是1/ln n。也就是说在不大于n的自然数里,总共的素数为 n/lgn

筛法:

  用筛法求素数的基本思想是(本质上也能算是一种预处理):把从1开始的、某一范围内的正整数从小到大顺序排列, 1不是素数,首先把它筛掉。剩下的数中选择最小的数是素数,然后去掉它的倍数。依次类推,直到筛子为空时结束。如有:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30。

  1不是素数,去掉。剩下的数中2最小,是素数,去掉2的倍数,余下的数是:3 5 7 9 11 13 15 17 19 21 23 25 27 29 。剩下的数中3最小,是素数,去掉3的倍数,如此下去直到所有的数都被筛完,求出的素数为:2 3 5 7 11 13 17 19 23 29。

题目:第十万零二个素数

  请问,第100002(十万零二)个素数是多少?   请注意:“2” 是第一素数,“3” 是第二个素数,依此类推。

  代码:

public class 第十万零二个素数 {

    public static void main(String[] args) {
        long now = System.currentTimeMillis();
        // nlognlogn
        f(100002);
        System.out.println("耗时:" + (System.currentTimeMillis() - now) + "ms");
        
        /*============Java自带的api==========*/
        now = System.currentTimeMillis();
        BigInteger bigInteger = new BigInteger("1");
        for (int i = 1; i <= 100002; i++) {
            bigInteger = bigInteger.nextProbablePrime();
        }
        System.out.println(bigInteger);
        System.out.println("耗时:" + (System.currentTimeMillis() - now) + "ms");
        
        /*==========朴素解法=========*/
        now = System.currentTimeMillis();
        int count = 0;
        long x = 2;
        while(count<100002){
            if (isPrime(x)) {
                count++;
            }
            x++;
        }
        System.out.println(x-1);
        System.out.println("耗时:" + (System.currentTimeMillis() - now) + "ms");
    }
    public static boolean isPrime(long num){
        for (int i = 2; i*i <= num; i++) {
            if (num%i==0) {
                return false;
            }
        }
        return true;
    }
    /**
     * 
     * @param N 第N个素
     */
    private static void f(int N){
        int n = 2;
        // 自然数n之内的素数个数n/ln(n)
        // 得到整数范围
        while(n/Math.log(n)<N){
            n++;
        }
        int []arr = new int[n];
        int x = 2;
        while(x<n){
            if (arr[x]!=0) {
                x++;
                continue;
            }
            int k=2;
             //对每个x,我们从2倍开始,对x的k倍,全部标记为-1
            while(x*k<n){
                arr[x*k] = -1;
                k++;
            }
            x++;
        }
        // System.out.println(arr);
        // 筛完之后,这个很长的数组里面非素数下标对应的值都是-1
        int sum = 0;
        for (int i = 2; i < arr.length; i++) {
            // 是素数,计数+1
            if (arr[i] == 0) {
                // System.out.println(i);
                sum++;
            }
            if (sum == N) {
                System.out.println(i);
                return;
            }
        }
    }

}

  结果:

猜你喜欢

转载自blog.csdn.net/OpenStack_/article/details/88729938