用Java显示前200个Prime数字

时间:2013-10-05 10:02:23

标签: java

您好我在使用java时遇到了一些问题,并让它显示前200个Prime数字。 我现在拥有的是一个限制为200个数字的代码,它将从200个数字中选择素数。 但是,如果我想要准确显示200个素数呢?

我有一个代码,里面有两个方法。第一种方法着重于显示数字,第二种方法着重于确定数字是否是素数。 如果确实如此,则会将其返回到方法1。

所以我试图做的是在for循环中创建一个计数器和一个while循环。 只有它导致只给出1个特定数字200次,所以我使用评论//来阻止while代码。

public static void main (String[] args)
{

    int limit = 200;
    for (int getal =2; getal<=limit; getal++)
    {
    //int count = 0;
    //while (count < 201)

        if (Priem(getal))
        {
            //count++;
            System.out.println(getal);
        }
    }

}   

public static boolean Priem (int getal)
{

    for (int i=2; i<getal; i++)
    {

        if (getal%i == 0)
        {
        return false;
        }

    }
    return true;
}

任何人都有任何想法如何解决这个问题?谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

试试这个:

public static void main (String[] args)
{

int countofPrime = 0;
for (int getal =2; ; getal++)
{
//int count = 0;
//while (count < 201)

    if (Priem(getal))
    {
        countofPrime++;
        System.out.println(getal);
        if(countofPrime == 200)
            break;
    }
}

}   

public static boolean Priem (int getal)
{

for (int i=2; i<getal; i++)
{

    if (getal%i == 0)
    {
    return false;
    }

}
return true;
}

答案 1 :(得分:1)

您可以使用Sieve of Eratosthenes算法。这是显示尽可能多的素数的好方法。