0 votes
Can someone help me with the code to find the nth prime number in Java? I am practicing for a coding competition and was stuck with this! I tried few things but those exceeded the time limit. So can someone help me with the problem? Mar 4, 2019 in Java 22,374 views

## 1 answer to this question.

+1 vote

Here is the code to find nth prime number.

```import java.util.Scanner;
public class NthPrime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n to compute the nth prime number: ");
int nth = sc.nextInt();
int num, count, i;
num=1;
count=0;

while (count < nth){
num=num+1;
for (i = 2; i <= num; i++){ //Here we will loop from 2 to num
if (num % i == 0) {
break;
}
}
if ( i == num){//if it is a prime number
count = count+1;
}
}
System.out.println("Value of nth prime: " + num);
}
}```

Output:

```Enter n to compute the nth prime number: 5
Value of nth prime: 11``` answered Mar 4, 2019 by
• 58,100 points
Can you please explain the logic??
The logic is simple. First, you take input from the user asking the value of n. Then you run a loop finding all the prime numbers. Whenever a prime number is found, the count is increased and if the count is equal to the input of user (i.e., if the prime number found is the nth prime number), then print it.

0 votes
2 answers

## How can we add leading zeros to the number in Java?

From Java 1.5 you can use the String.format method. ...READ MORE

0 votes
1 answer

## In Java, how to find out the min/max values from array of primitive data types?

import java.util.Arrays; import java.util.Collections; import org.apache.commons.lang.ArrayUtils; public class MinMaxValue { ...READ MORE

0 votes
2 answers

## How to round any number to n decimal places in Java?

new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP); will get you a BigDecimal. To ...READ MORE

0 votes
1 answer

## How to print java array in the simplest way?

String[] arr = new String[] {"John", "Mary", ...READ MORE

0 votes
1 answer

## Are arrays equivalent to objects in Java ?

Yes; the Java Language Specification writes: In the Java ...READ MORE

0 votes
1 answer

## Remove objects from an array in Java?

We can use external libraries: org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int ...READ MORE

0 votes
1 answer

## Performance difference of if/else vs switch statement in Java

The thing you are worried about is ...READ MORE

+1 vote
3 answers

## What is the syntax to declare and initialize an array in java?

You can use this method: String[] strs = ...READ MORE

+4 votes
1 answer

## How to print the individual occurance of elements in Java?

You can use a HashMap to serve ...READ MORE

+15 votes
25 answers

## How can I convert String to JSON object in Java?

Hi @Daisy You can use Google gson  for more ...READ MORE