Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+7 votes
2 views
in Java by (47.6k points)

Can someone help me with the code to find the nth prime number in Java? I am practising for a coding competition and was stuck with this! I tried a few things but those exceeded the time limit. So can someone help me with the problem?

1 Answer

+7 votes
by (106k points)

You can use the below mentioned-code to find the 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++){

        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);

  }

} 

Related questions

0 votes
1 answer
asked Mar 19, 2021 in Java by sheela_singh (9.5k points)
0 votes
0 answers
asked Feb 18, 2021 in Java by Harsh (1.5k points)
0 votes
1 answer
0 votes
1 answer
asked Dec 17, 2020 in Python by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...