This java program is the solution to Project Euler’s problem-7. It can be found here The problem:

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?

We basically run through a while loop to check if each number is a prime number or not. If the number is prime, we increment the **prime_count** counter variable. We execute the while loop until prime_count becomes 10001.

There are some enhancements done to the Prime() method. One of the major one being at line 6. The line prevents our program from doing a lot of iterations.

1 |
int sqrt_num = (int) (Math.sqrt(num))+1; |

Program:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
/* * Author: Vlad * website: www.mycoding.net * */ import java.math.*; public class Euler_7 { public static boolean Prime(long num){ if(num == 2) return true; if(num%2 == 0 || num == 1) return false; int sqrt_num = (int) (Math.sqrt(num))+1; for(int i=3; i<sqrt_num; i++){ if(num%i==0) return false; } //end for return true; } //end Prime() public static void main(String[] args) { long a=1; long ans =0; int prime_count = 0; while(prime_count<= 10001){ if(Prime(a)){ prime_count++; ans = a; } a++; } //end while System.out.println("10001st prime number: "+ans); }//end Main } //end class |

The following two tabs change content below.

#### Vlad

#### Latest posts by Vlad (see all)

- Code jam “Tic-Tac-Toe-Tomek” solution in java - April 19, 2013
- Code jam “Minimum Scalar product” solution in java - March 18, 2013
- Code jam Store Credit solution in java - March 10, 2013

but the 10 001st prime is 104743