zoukankan      html  css  js  c++  java
  • java实现找素数

    ** 找素数**

    素数就是不能再进行等分的整数。比如:7,11。而9不是素数,因为它可以平分为3等份。一般认为最小的素数是2,接着是3,5,…
    请问,第100002(十万零二)个素数是多少?
    请注意:“2” 是第一素数,“3” 是第二个素数,依此类推。
    不需要提交源代码,只要写出准确的结果即可!
    答案写在:“解答.txt”中,不要写在这里。

    参考答案:
    1299743

    import java.math.BigInteger;
    
    public class Main1 {
        //方法1:使用大整数,自带判断素数方法,算出最终结果大约要1分钟
        public void printResult1() {
            int count = 1;
            BigInteger a = new BigInteger("3");
            BigInteger b = BigInteger.ONE;
            for(int i = 3;i < 10000000;i++){
                if(a.isProbablePrime(i)) {
                    count++;
                }
                if(count == 100002) {
                    System.out.println(a);
                    break;
                }
                a = a.add(b);
            }
            return;
        }
        
        //方法2:使用埃拉托色尼筛选法,算出结果大约10秒
        public void printResult2() {
            int[] A = new int[10000000];
            for(int i = 2;i < 10000000;i++)
                A[i] = i;
            
            for(int i = 2;i < 4000;i++) { // 4000 * 4000 > 10000000,此处是因为i*i为i的当前条件下最小合数
                int j = 0;
                if(A[i] != 0)
                    j = i * i;  //i的合数起始最小位置
                while(j < 10000000) {
                    A[j] = 0;
                    j = j + i;   //依次递增i个位置的数均是i的合数
                }
                
            }
            
            int count = 0;
            for(int i = 2;i < 10000000;i++) {
                if(A[i] != 0) 
                    count++;
                if(count == 100002) {
                    System.out.println(A[i]);
                    break;
                }
            }
            return;
        }
        
        public static void main(String[] args) {
            Main1 test = new Main1();
            test.printResult2();
        }
    }
    
  • 相关阅读:
    spsss基本统计分析操作攻略
    MATLAB读取Excel表格数据和处理数据
    MATLAB 雷达图画图函数
    spss新手教程
    MATLAB绘制饼状图
    高斯消元法解线性方程组(C++实现)
    Java和matlab混合编程
    Matlab与Java混合编程的教程
    两组数据的相关性分析
    vs2013+QT5环境
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13077042.html
Copyright © 2011-2022 走看看