Home > Software design >  Missing some statements in my code that is keeping me from completing this code
Missing some statements in my code that is keeping me from completing this code

Time:11-07

I am trying to complete this. A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided evenly by 1, 2, 3, and 6. Write a Boolean function named is_prime which takes an integer as an argument and returns true if the argument is a prime number, or false otherwise. Use the function in a program that prompts the user to enter a number then displays a message indicating whether the number is prime.

def main():
    #decribe the program
    print ("This is a program to see if a number is prime")
    #ask the user for a number
    number = int (input ("Enter a number to see if it prime: "))
    #see if the number is prime
    result = is_prime (number)
    print ("The number", number, "is", result)

def is_prime(number): 
    while number < 0:
        print ("The number must be greater than 1")
        number = int (input("Enter a valid number: "))
    
    for x in range (1, number   1):
        if (number % x) == 0:
            return False
        else: 
            return True
 
main()

In my for statement, I am missing something and having a hard time figuring out what I did wrong. What step am I missing?

CodePudding user response:

The range of numbers checked inside is_prime(number) cannot include the numbers (1, number), because any number is divisible by them. Additionally, you can only return True at the end of the for-loop if no divisors were found:

def is_prime(number): 
    ...

    for x in range (2, number):
        if (number % x) == 0:
            return False
     return True

For optimal execution speed, it can be proven that you only need to check numbers until sqrt(number):

from math import sqrt, ceil
def is_prime(number): 
    ...

    for x in range(2, min(number,1 ceil(sqrt(number)))):
        if (number % x) == 0:
            return False
    return True

CodePudding user response:

Try this code for the function is_prime:

def is_prime(number): 
    while number < 1:
        print ("The number must be greater than 1")
        number = int (input("Enter a valid number: "))
    
    for x in range (2, number):
        if number == 2:
            return True
        if (number % x) == 0:
            return False
    return True

Comment to my corrections:

  • 2 is prime
  • you have to exclude 1 and number so range(2, number) and not range (1, number 1)
  • while number < 1: better than while number < 0:
  • Related