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
The task is to find the Nth prime number given a number N.
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...read more
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 variabl...read more
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
- 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
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
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
Top UST Senior Software Engineer interview questions & answers
Popular interview questions of Senior Software Engineer
Reviews
Interviews
Salaries
Users/Month