196k views
3 votes
In Python: For assignment you are to implement the following two functions: IsPrime(num) This function tests the value of num to determine if it is a prime number. If num is prime, then the function returns the value True, otherwise it returns the value False. NthPrime(n) This function returns the nth prime number Using these two functions you are to implement an application that asks the user to input a value that will be used to find a prime number. For example, if the user inputs the value 5, the program will output the 5th prime number. Once this value has been output, the program should ask the user if they would like another prime number to be found and output. Each time the user responds in the affirmative by input "yes" the program should prompt the user to input another value for a prime to be found. This process should continue untill the user responds in the negative by inputting "no." If a value other than "yes" or "no" is input, the user should be reprompted to input a correct response.

1 Answer

4 votes

Final answer:

To implement the IsPrime(num) and NthPrime(n) functions in Python and create an application that finds prime numbers, you can use the provided code. The code checks whether a number is prime and finds the nth prime number. It also allows the user to continue finding prime numbers until they choose to stop.

Step-by-step explanation:

To implement the functions IsPrime(num) and NthPrime(n) in Python, you can use the following code:

import math

def IsPrime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True


def NthPrime(n):
count = 0
num = 2
while count < n:
if IsPrime(num):
count += 1
num += 1
return num - 1


# Example usage
prime_position = int(input('Enter the position of the prime number you want to find: '))
print(f'The {prime_position}th prime number is:', NthPrime(prime_position))

To prompt the user if they would like another prime number, you can use a while loop that checks the user's input and terminates if 'no' is entered.

User Yosef Weiner
by
7.5k points