Today I had an interview, where I was asked to solve this problem:
Generate nth prime number. Given a signature below, write python logic to generate the nth prime number:
def nth_prime_number(n): # n = 1 => return 2 # n = 4 => return 7 # n = 10 => return 29
I wrote this code, but couldn't get through:
def nth_prime_number(n):
if n==1:
return 2
count = 1
num = 3
while(count <= n):
if is_prime(num):
count +=1
if count == n:
return num
num +=2 #optimization
def is_prime(num):
factor = 2
while (factor < num):
if num%factor == 0:
return False
factor +=1
return True
The overall feedback was that the code quality could be improved a lot, and that I should be more optimal in my approach. How can I improve this code?