简体   繁体   中英

Returning whether or not a number is prime as a Boolean in Python

For context, I am trying to solve Project Euler problem 3 using Python:

What is the largest prime factor of the number 600851475143?

As a first step to this, I am trying to write a function that returns whether or not a number is prime as a Boolean. I made a first attempt, and checked out how this has been written previously. I have ended up with the following code:

def isprime(x):
    limit = x**0.5
    i = 2

    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        while i <= limit:
            if x%i == 0:          
                return False
                i = i + 1       
            else:
                return True

For some reason, the code above does not work perfectly. For example, isprime(99) would return True.

Please, can someone help me understand why this isn't working? I am trying to avoid just copying and pasting someone else's code, as I want to understand exactly what is going on here.

To me, it looks like the issue is with the final else statement. I say this because the logic reads "in the event that x%i == 0 , this number is not prime" but it doesn't explicitly say what to do in the event that no x%i iterations == 0 .

Any help on this would be appreciated, I'm not necessarily looking for the cleanest, neatest way of doing this. but more just trying to first make this code work.

Try this:

def isprime(x):
    limit = x**0.5
    i = 2
    if x <= 2:
        return False

    while i <= limit:
        if x%i == 0:          
            return False      
        i = i + 1
    return True 

I've changed many things. have this point in your mind that there is no need to else clauses when you return at the end of if block.

you need to tell what happens when x%i==0 condition not met and the value of i remain constant and also need to see when all conditions not met, then it is a prime

# your code goes here
def isprime(x):
    limit = x**0.5
    i = 2

    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        while i <= limit:
            if x%i == 0:         
                return False
            i+=1
    return True
print(isprime(144)) # false
print(isprime(99)) # false
print(isprime(131)) # true

Just to show an alternative, what you could do is checking from number 2 to your number if the operation (x % i) is equal to zero. If it never happend, it will be a prime.

def isprime(x):
   # check for factors
   for i in range(2,x):
       if (x % i) == 0:
           return False
   else:
       return True

print(isprime(99))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM