Yes
Yes

Reputation: 25

I dont know why but when I run the following code it return 9 as a prime number

Im supposed to make a function that takes an integer and returns if its a prime or not but for some reason it returns 9 as a prime

def prime(x):
    if x == 0 or x == 1:
        return "not prime"
    elif x == 2:
           return "prime"
    else:
      for numbers in range(2,x):
       if x % numbers == 0:
            return "not prime"
       else:
            return "prime"

for i in range(20):
    print (i, prime(i))

Upvotes: 1

Views: 86

Answers (2)

Kyle Alm
Kyle Alm

Reputation: 587

Your code will return an answer on the first iteration, at which point it stops iterating:

for numbers in range(2,x):
  if x % numbers == 0:
    return "not prime"
  else:
    return "prime"

This starts with 2, and if it goes into x evenly, it returns not prime, if not it returns prime, and either way it stops.

for numbers in range(2,x):
  if x % numbers == 0:
    return "not prime"
return "prime"

This would do the trick, though, as it will only return "prime" if none of the numbers returned "not prime".

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140256

The first numbers are either even or prime.

9 is the first number where the bug in your code really shows.

The bug is: you return "prime" if one test fails. Since 9 % 2 is not 0, the test fails there.

rewrite (naively) as:

  for numbers in range(2,x):
     if x % numbers == 0:
          return "not prime"
  return "prime"

so if the loop ends without returning the number is prime.

Note that there are better & faster ways to test primality. For instance, don't loop up to x-1 but to square root of x (included), since there can't exist divisors after that value.

 for numbers in range(2,int(x**0.5)+1):

Upvotes: 2

Related Questions