Find the 10001st prime.

Project Euler Problem 7: 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 10001st prime number?
Solution: We use a brute force approach to find prime numbers. We find a prime number and find another prime by dividing the next number with the currently obtained prime nos.


Java implementation of above is as follows:


class Prime10001{
int count=0;
int nextPrime(int x){
//starting from current prime(i.e prime) find next prime
for(int i=x;;i++)
/* check if no. being checked is divisible
by any no. less than or only itself */
for(int j=2;j<=i;j++){
/* check if no. being checked(i) is
divisible by any other no. */
if(i%j==0){
/* check if the no. is divisible only by itself
or anyother no. if yes go to next no. */
if(i!=j)
break;
else {
x=i;
System.out.println("Current prime no. is " + x);
return x;
}
}
}
}
}
class Test7{
public static void main(String [] args){
Prime10001 l = new Prime10001();
long prime = 2;
while(l.count<10001){
prime = l.nextPrime((int)prime);
prime++;
l.count++;
}
System.out.println("The 10001st prime is: "+prime);
}
}

Keep Coding !!!

Leave a Reply

Your email address will not be published. Required fields are marked *