Java Program - Nth Prime Number
This program finds the Nth prime number.
This program finds the Nth prime number.
public class NthPrimeNumber {
public static void main(String[] args) {
int n = 10;
int count = 0, num = 1, i;
while (count < n) {
num++;
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
break;
}
}
if (i > num / 2) {
count++;
}
}
System.out.println("The " + n + "th prime number is: " + num);
}
}
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.