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


#1
def is_prime(x):
    i=0
    if x==0 or x==1:
        return False
    elif x==2 or x==3:
        return True
    else:
        for n in range(2, x-1):
            if x % n != 0:
                i+=1
        if x-2==i:
            return True
        else:
            return False

Hi everyone,
my code above works this way:
I defined a counter named "i", it counts the number of remainders. as a Prime number we must have remainder in each division from 2 up to the number (except itself). so the number of remainder must be "number-2".
this is how I wrote my algorithm and I don't know why it gets an error! the error says : Oops, try again. Your function fails on is_prime(5). It returns False when it should return True.

Any help would be appreciated

Sarah


#2

Well, you should change it a bit.

  1. First, let's check to see if the number is less than 1
  2. Then let's check to see if it is 2
  3. Then let's see if the number is divisible by 2
  4. Then starting at 3, let's see what odd numbers can divide into our number up to the square root of the number plus 1

Take a gander at this post too,

Here is the code following my steps.

EXAMPLE:

from math import sqrt

def is_prime(number):
    if number > 1:
        if number == 2:
            return True
        if number % 2 == 0:
            return False
        for current in range(3, int(sqrt(number) + 1), 2):
            if number % current == 0:
                return False
        return True
    return False

#3

thanks for your help..
but I think there should be lots of way to write this code.. I feel confused about your number 4! I rather to not write a code which I don't understand! and I think my code is logically correct (at least I think this way)! so I wanna know the problem with my Code!...


#4

Take a look at the link I provided, it shows that the formula is good all the way to 10,000,000,000 so that basically covers all the primes we will be dealing with.

As to why, because we already checked if the number was greater than one and if the number is two or divisible by two we can start at three.

Also because we already checked if the number was divisible by two we just have to do the odd numbers because we already did ALL even numbers.

Also your logic is flawed.

So in order to make this statement true you have to have fullfill it's condition.

Let's test some numbers,

# 5
is_prime(5)
# i == 2
# x - 2 == 3
False

As you can see your logic is flawed, if you do not understand what your program is doing add logging/debugging code to it to see what you have it doing.


#5

lol, I found the solution... at line 8, I should have write:
for n in range(2,x)
instead of:
for n in range(2,x-1)

hahaa!!