7.Prime Number

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see  that the 6th prime is 13. What is the 10 001st prime number?

public class Problem7 {
    public void primePE() {
        long limit=10001,count =1, p=1;
        do  {
            p+=2;
            if (isPrime(p)) 
                count+=1;
        } while (count<limit);
       System.out.println(p);
    }

    public boolean isPrime(long n) {
        if(n==1) 
            return false;
        else if (n<4)
            return true; //2 and 3 are prime
        else if (n%2==0)
            return false;
        else if (n<9)
            return true; //we have already excluded 4,6 and 8.
        else if (n%3==0)
            return false;
        else {
            double r=Math.floor(Math.sqrt(n)); // n rounded to the greatest integer r so that r*r<=n
            double f=5;
            while(f<=r) {
                if (n%f==0)
                        return false;// (and step out of the function)
                if (n %(f+2)==0) 
                    return false; //(and step out of the function)
                f=f+6;
            }
        }
        return true; //(in all other cases)
    }

    public static void main(String[] args) {
        Problem7 p = new Problem7();
        p.primePE();
    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: