-2

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

我有一个代码,其中有 2 个方法。第一种方法侧重于显示数字,第二种方法侧重于确定数字是否为质数。如果为真,它将返回到方法 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;
}

有人知道如何解决这个问题吗?谢谢您的帮助!

4

2 回答 2

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;
}
于 2013-10-05T10:04:39.510 回答
1

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

于 2013-10-05T10:07:51.883 回答