Complete the code to find if a given number is a prime number? The program will take a positive integer greater than 1 as input and indicate if it is a prime number by saying "prime", and if it is not a prime number saying "not a prime". Note there are 3 places in the given code that you need to fix for this code to work properly and give the expected output.
Question
Complete the code to find if a given number is a prime number? The program will take a positive integer greater than 1 as input and indicate if it is a prime number by saying "prime", and if it is not a prime number saying "not a prime". Note there are 3 places in the given code that you need to fix for this code to work properly and give the expected output.
Solution
Sure, here is the corrected code:
def is_prime(n):
if n > 1:
for i in range(2, n):
if (n % i) == 0:
return "not a prime"
break
else:
return "prime"
else:
return "not a prime"
# Test the function
print(is_prime(5)) # Should print "prime"
print(is_prime(4)) # Should print "not a prime"
Here are the corrections:
- The function
is_primewas defined to check if a number is prime or not. - The
forloop was used to check if the number is divisible by any number up to itself. If it is, then it's not a prime number and the function returns "not a prime". - If the number is not divisible by any number up to itself, then it's a prime number and the function returns "prime".
Similar Questions
write easies code for me : Write a program in C to find if a number is prime or not.
Write a program primes.py that reads a positive integer from standard input, and determines whether or not the number is prime.A prime number is a positive integer that is:greater than 1, andcan be divided exactly (without leaving a remainder) only by 1 or itself.
Problem Statement:Find whether the given number is prime or not.Input Format:Accept an integer as inputOutput Format:Print the output as "Prime Number" or "Not a Prime Number"Constraints:1 <= INPUT <=10^15Sample Input 1:31Sample Output 1:Prime NumberSample Input 2:2Sample Output 2:Prime NumberSample Input 3:15Sample Output 3:Not a Prime Number
What are looping statements. Write a program to check whether a number is prime no. or not.
Test 1: Check1 for the positive number input which is not a prime number. Also check for the case and spacing in input and output statements.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.