码迷,mamicode.com
首页 > 其他好文 > 详细

输出第N个素数

时间:2016-02-20 22:57:05      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:

输出第N个素数

public class FindNthPrime
{
    public static void main(String[] args){
        int N = Integer.parseInt(args[0]); //要求输出第 N 个素数
        int[] PrimesVector = new int[N]; // 存储已经找到的素数
        PrimesVector[0] = 2; //第一个素数是2
        int CntPrime = 1; //目前找到的素数的数目是1
        for(int i = 3; CntPrime < N; i++)
        {
            boolean isPrime = true;
            // 因为非素数可以拆成素数的乘积,所以只需要考虑已经找到的素数
            for (int j = 0; j < CntPrime && PrimesVector[j]*PrimesVector[j] <= i; j++) 
            {
                if ( i % PrimesVector[j] == 0)
                {
                    isPrime = false;
                    break; //跳出循环
                }
            }
            if (isPrime)
            {
                CntPrime++;
                PrimesVector[CntPrime-1] = i;
            }
        }       
        System.out.println(" The " + N + "th prime is " + PrimesVector[N-1]);
    }
}

测试结果

技术分享

输出第N个素数

标签:

原文地址:http://www.cnblogs.com/learning-c/p/5204077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!