-6
print "Type a number"
num = int(raw_input("> "))

if num % 2 == 0:
    print "This is not a prime number"

else:
    print "This is a prime number"

When I type '9' it says it's a prime number, which it isn't:

Type a number
> 9
This is a prime number

Is my code too simple? Is there something it doesn't check?

javanewbie
  • 281
  • 1
  • 3
  • 12
  • 1
    Because this is not a prime number checker. You're basically checking even or odd, and 9 is odd. – FatalError Nov 16 '16 at 16:02
  • Your program asks "is this number divisible by 2? If not, it's prime". That's why it counts 9 as a prime. Perhaps look into the [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) for a simple prime checker? – Aurora0001 Nov 16 '16 at 16:02
  • Your code doesn't check prime numbers, it checks if a number is even or odd. – user2393256 Nov 16 '16 at 16:02
  • 1
    Your program is only checking if the number inputted is divisible by 2 or not. Which actually checks for even number. Not prime. – Imtiaz Raqib Nov 16 '16 at 16:03

4 Answers4

4

You're only checking if it is an even number, by checking if it is divisible by 2. But 9 is divisible by 3 so you need to check that also. The easiest way would be to check all numbers up to the square root of the number you're checking for primality.

Eric
  • 77
  • 1
  • 5
4

All you are doing here is checking whether or not a number is evenly divisible by 2. Since 9 / 2 = 4.5, it's not evenly divisible by 2 thus going to the else clause.

Here is a condensed, working version of what you probably want:

def is_prime(a):
    return all(a % i for i in xrange(2, a))
Scriptomaniac
  • 207
  • 1
  • 2
  • 10
2

To check if number is prime you have to validate is it devisible by any number in range [2, sqrt(n)].

Following code does exactly the same:

import math

def is_prime(n):
    for i in range(2, int(math.sqrt(n))+1):
        if n % i == 0:
            return False
    return True

This method is good for small number, but if n is real big number then you need something faster. And in this case you can use Miller–Rabin primality test which checks primality with a certain probability.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
1

You are checking if a given number is even or not, and 9 is not even so your code prints out "This is a prime number"

Please take a look at this Stackoverflow question for a detailed explanation on how to check for prime numbers using Python.

Community
  • 1
  • 1
McMutton
  • 905
  • 13
  • 25