Java程序中应该显示第10,000个素数的错误?

时间:2014-10-07 00:58:24

标签: java loops primes

这是我的代码,不知道出了什么问题!我犯过什么错误?

BTW:此代码中的第一个程序旨在计算小于1,000的素数,以避免混淆。

public class AnalyzingPrime
{

    public static boolean isPrime (int n)
    {
        if (n==1)
        return false;
        for (int i = 2; i < n; i++)
        {
            if (n%i==0)
            return false;
        }
        return true;

    }

    public static void main (String [] args)
    {
        int numberofPrimes = 0;
        int counter = 0;
        int number = 10000;
        for (int i = 2; i <= number; i++)
        {
            if (isPrime(i) == true)
            {
                counter++;
            }
        }
        System.out.println("There are "+counter+" prime numbers.");
        System.out.println("And if you care, the 10,000nth prime number is "+ nthPrime(10000)+".");
    }

    public static int nthPrime (int n)
    {
        int i = 0;
        int nthcounter = 0;

        while (nthcounter <= n)
        {
            i++;
            if(isPrime(i) == true)
            {
                nthcounter++;
            }
        }

        return nthcounter;
    }
}

2 个答案:

答案 0 :(得分:1)

我认为没有错误,它的方法不正确。

public static int nthPrime (int n)
{
    int i = 0;
    int nthcounter = 0;

    while (nthcounter != n) //when total prime number equal to 10000, stop loop
    {

        if(isPrime(i) == true)
        {
            nthcounter++;
        }
        i++;
    }
    return i;
}

您应该返回i而不是nthcounter

答案 1 :(得分:0)

你的while循环检查和返回值有问题。

public class AnalyzingPrime
{

    public static boolean isPrime (int n)
    {
        if (n==1)
        return false;
        for (int i = 2; i < n; i++)
        {
            if (n%i==0)
            return false;
        }
        return true;

    }

    public static void main (String [] args)
    {
        int numberofPrimes = 0;
        int counter = 0;
        int number = 10000;
        //add the variable to control which prime number you want
        int primeCount = 4;
        for (int i = 2; i <= number; i++)
        {
            if (isPrime(i) == true)
            {
                counter++;
            }
        }
        System.out.println("There are "+counter+" prime numbers.");
        System.out.println("And if you care, the " + primeCount + "th prime number is "+ nthPrime(primeCount)+".");
    }

    public static int nthPrime (int n)
    {
        //if you know 1 is not prime number then why start with 0
        int i = 1;
        int nthcounter = 0;

        //should not be <= but < because when equal should not go inside the while loop
        while (nthcounter < n)
        {
            i++;
            if(isPrime(i) == true)
            {
                nthcounter++;
            }
        }

        //should not return the counter but the prime value you want
        return i;
    }
}