简体   繁体   中英

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.

I need help finding the problem. What can I change so it finds the 10001st prime number ? 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.

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

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. And then, you don't really need to test for i=0.

An extra a++ is done in the while - loop, when prime == 10001 .

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

You can use --a to print the prime you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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