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
Approach (Using Sieve of Eratosthenes) :
1) We'll create a global sieve and store values of prime numbers in it and use it to get prime numbers for all queries in constant time.
2) Define global variab...read more
CodingNinjas
author
2y
Brute Force
Consider a function FINDPRIME that takes number N as input parameter and do:
- Initialize NUM to 1 and COUNT to 0.
- Iterate for COUNT, while COUNT<=N:
- Increment NUM by 1
- Iterate for each 2<= i <= ...read more
CodingNinjas
author
2y
Sieve of Eratosthenes
- Define MAXSIZE as 10^6+5 and an empty ARRAYOFPRIMES.
- Initialize boolean array ISPRIME[i] to TRUE for each 2<=i <=MAXSIZE
- Iterate for each 2 <= p <= MAXSIZE:
- 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:
- Define ArrayLists ISPRIME, PRIMENUMBER and SPF (Smallest Prime Factor).
- Set ISPRIME false for 0 and ...read more
Add answer anonymously...
Top Siemens Senior Systems Engineer interview questions & answers
Popular interview questions of Senior Systems Engineer
Top HR questions asked in Siemens Senior Systems Engineer
Stay ahead in your career. Get AmbitionBox app
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