Is_prime: Working Fine. But not for 3 as a Prime Number


def is_prime(x):
    if x == 1:
        return True
        n= 2
        for a in range(n,x-1):
            if x % a == 0:
                return False
        return True

Following code is working fine for every number and I am getting True of False regarding the number I enter but there is a single Problem. I am not getting return value for 3. Can someone please help.

is_prime: why doesn't it work?
Why does one code work for prime numbers, and the other doesn't?
6. is prime

Change your code to reflect that, you have to tell it when your number is equal to 3 it is a prime!

Here is a code sample I created and here is the theory behind it, it can theroicaly find primes up to 10,000,000,000


Here is a link to a post on codeacademy.

def is_prime(number):
    This function computes all the whole numbers from 3 to the square root of the
    number + 1, this takes out a bunch of un-need computations.
    :param number: Number to be computed
    :return: Returns True if is prime Else False
    if number > 1:
        # This line checks if the number is greater than one, if not returns False
        if number == 2:
            # This line checks to see if the number is 2, if so Returns True
            return True
        if number % 2 == 0:
            # This line checks to see of the number is divisible by two if so Returns False
            return False
        for current in range(3, int(sqrt(number) + 1), 2):
            # This line iterates through the range of numbers from 3 to the square root of
            # the number + 1 with a stride of two
            # So numbers would be non-even numbers
            if number % current == 0:
                # If a number divides into our number Returns False
                return False
        return True
        # Returns True if non of the previous tests failed
    return False

6/15 is_prime code doesn't works
6-15 is_prime, I don't know what's wrong with my code!

:grinning: Looks like you are having PhD in Prime numbers. Buy the way thanks for the solution.
I have seen your precious solution inn the codecademy link but I did not got the understanding of the use of

for current in range(3, int(sqrt(number) + 1), 2):

Can you please describe it in detail.


If you follow that link, it basically states that you can find if a number is prime all the way up to 10,000,000,000 if you use that method.

The method states that you first eliminate all even numbers then cycle through all odd number to the square root of your number. That will have all the data needed to determine if a number is prime all the way to 10,000,000,000, past that it will only tell you if it is a possible prime.


Oops, try again. Did you create a function called is_prime? Your code threw a "global name 'sqrt' is not defined" error.