Find Nth Prime

You are given a number 'N'. Your task is to find Nth prime number.

A prime number is a number greater than 1 that is not a product of two smaller natural numbers. Prime numbers have only two factors – 1 and the number itself.

Any number greater than 0 is a natural number i.e. natural numbers N = {1, 2, 3, 4,....}

For example:-

If you are asked to find the 7th prime number, it’ll be 17 because the first 7 prime numbers are 2, 3, 5, 7, 11, 13, 17.

Note: 1 is not a prime number.

Follow Up:
Try to solve the problem in O(N).
Input Format :
The first line of input contains an integer 'Q' representing the number of the queries. Then the queries follow:

The first line of each query contains an integers ‘N’ representing the number of a prime number to be found.
Output Format :
For each query, return the Nth prime number. 

Print the output of each query in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= Q <= 100
1 <= N <= 10^4

Time Limit: 1 sec
CodingNinjas
author
2y

Step 1  I opted for the Sieve of Eratosthenes approach.
Step 2  Store all prime numbers in a vector and return (n-1)th for Nth Prime Number.

CodingNinjas
author
2y
Brute Force

Consider a function FINDPRIME that takes number N as input parameter and do:

  1. Initialize NUM to 1 and COUNT to 0.
  2. Iterate for COUNT, while COUNT<=N:
    1. Increment NUM by 1
    2. Iterate for each 2<= i <= ...read more
CodingNinjas
author
2y
Sieve of Eratosthenes
  1. Define MAXSIZE as 10^6+5 and an empty ARRAYOFPRIMES.
  2. Initialize boolean array ISPRIME[i] to TRUE for each 2<=i <=MAXSIZE
  3. Iterate for each 2 <= p <= MAXSIZE:
    1. If IsPrime[P] is not cha...read more
CodingNinjas
author
2y
Global Sieve of Eratosthenes

We can use some basic OOPs techniques to reduce complexity. We'll create a global sieve and store values of prime numbers in it and use it to get prime numbers for all que...read more

CodingNinjas
author
2y
Modified global sieve

Consider function FINDNTHPRIME that accepts an integer N as a parameter and do:

  1. Define ArrayLists ISPRIME, PRIMENUMBER and SPF (Smallest Prime Factor).
  2. Set ISPRIME false for 0 and ...read more
Add answer anonymously...
Nagarro Technical Trainee Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter