codeforces 327B(Hungry Sequence) 素数筛法入门(欧拉筛法) Java

来源:互联网 发布:辐射4优化补丁 编辑:程序博客网 时间:2024/05/29 08:03

简单的素数筛法–推荐使用欧拉筛法【点蓝色字体查看详情】

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.util.Scanner;/** * 题意:输出一个数列,要求递增的并且后面的数不能被它前面的数整除。 *  * 分析:可以输出 n 个递增的质数,使用素数筛法。 *  * 注意:如果有多个解决方案,您可以输出任何一个。即与样例输出不相同也有可能是正确的。 *  * @author TinyDolphin * */public class Main {    private static final int MAX_LENGTH_CHECK = 100000000; // 亿    private static final int MAX_LENGTH_PRIMELIST = 10000000; // 千万    private static boolean[] check = new boolean[MAX_LENGTH_CHECK]; // 存储标记    private static int[] primeList = new int[MAX_LENGTH_PRIMELIST]; // 存储素数    /**     * 欧拉筛法:保证每个合数只会被它的最小质因数筛掉,时间复杂度降低到O(n)。      * 每一个数都去乘以当前素数表里面已有的数,     * 当 indexI 是合数,且indexI % primeList[indexJ] == 0 时,只能乘以第一个素数 2     */    private static void Euler(int num) {        int count = 0;        for (int indexI = 2; indexI <= num; indexI++) {            if (!check[indexI]) {                primeList[count++] = indexI;            }            // 每一个数都去乘以当前素数表里面已有的数,如果 indexI 是合数,            // 且 indexI % primeList[indexJ] == 0,那么它只能乘以第一个素数 2            // 如:2×2、3×(2、3)、4×(2)、5×(2、3、5)、6×(2)、7×(2、3、5、7)、8×(2)、9×(2、3)、10×(2)            for (int indexJ = 0; indexJ < count; indexJ++) {                // 过大的时候跳出                if (indexI * primeList[indexJ] > num) {                    break;                }                check[indexI * primeList[indexJ]] = true;                // 如果 indexI 是一个合数,而且 indexI % primeList[indexJ] == 0                // 保证了每个合数只会被它的最小素因子筛掉                if (indexI % primeList[indexJ] == 0) {                    break;                }            }        }    }    public static void main(String[] args) {        Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));        int inputN;        Euler(10000000);        while (in.hasNext()) {            inputN = in.nextInt();            for (int index = 0; index < inputN; index++) {                out.println(primeList[index]);            }        }        out.flush();    }}
阅读全文
0 0