简体   繁体   English

小错误10001st素数Java代码?

[英]Small error 10001st prime number java code?

I have to find the 10001st prime number which is 104753 but when I run my code I get 104754. 我必须找到10001st质数,即104753,但是当我运行代码时,我得到104754。

I need help finding the problem. 我需要寻找问题的帮助。 What can I change so it finds the 10001st prime number ? 我可以更改什么才能找到第10001个素数? Thanks 谢谢

This is what I've done so far : 到目前为止,这是我所做的:

public class Prime
{

    public static void main(String[] args)
    {
        int a = 1;
        int primes = 0;

        while (primes < 10001)
        {
            if (isPrime(a) == true)
            {
                primes++;
            }

            a++;
        }

        System.out.println("The 10001st prime number is " + a);
    }

    public static boolean isPrime(int b)
    {
        boolean x = false;
        int counter = 0;

        for (int i=1; i<=b; i++)
        {
            if (b%i == 0)
            {
                counter++;
            }

            if (counter == 2 && i == b)
            {
                x = true;
            }
        }

        return x;
    }
}

Right after you find the number, you increment it. 找到数字后,立即增加它。

if(isPrime(a) == true)
{
    primes++;
}
    a++;

You should print it before incrementing it. 您应该在递增之前打印它。

You increment 'a' after determining whether it is prime. 确定是否为质数后,可以递增“ a”。

If this were my project I would start with: 如果这是我的项目,我将从以下内容开始:

a = 0;

and then in my loop I would: 然后在我的循环中,我将:

a++;
if (isPrime(a)) {
    count++;
}

One simple solution: 一种简单的解决方案:

int a = 0;
int primes = 0;
while(primes < 10001) {
    a++;
    if(isPrime(a) == true) {
        primes++;
    }
}

Of course there are many others. 当然还有很多其他的。 Perhaps your should also consider faster algorithms that find prime numbers: 也许您还应该考虑找到质数的更快算法:

http://www.wikihow.com/Check-if-a-Number-Is-Prime http://www.wikihow.com/Check-if-a-Number-Is-Prime

And as a start, make sure to exit early in your isPrime test method: If you reach a point during the loop where your counter is higher than 2, you can exit. 首先,请确保在isPrime测试方法中尽早退出:如果在循环过程中到达计数器高于2的点,则可以退出。 And then, you don't really need to test for i=0. 然后,您实际上不需要测试i = 0。

An extra a++ is done in the while - loop, when prime == 10001 . prime == 10001时,在while循环中执行了一个额外的a++

 while (primes < 10001) {
        if (isPrime(a)) {
            primes++;
        }
        a++;
 }

You can use --a to print the prime you want. 您可以使用--a打印所需的质数。

System.out.println("The 10001st prime number is " + (--a));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM