3

I've written this very simple prime number check:

prime = int(input())
if prime % prime == 0 and prime % 2 != 0 and prime % 3 != 0 or prime == 2 or prime == 3:
    print("true")
else:
    print("false")

... which seems to work somehow, but i'm not certain if its the correct way, can someone please confirm?

3 Answers3

6

As simple as it gets:

def isprime(n):
    """check if integer n is a prime"""
    # range starts with 2 and only needs to go up the squareroot of n
    for x in xrange(2, int(n**0.5)+1):
        if n % x == 0:
            return False
    return True

For an impressive prime-number generator, see here

Community
  • 1
  • 1
Fredrik Pihl
  • 41,002
  • 6
  • 73
  • 121
5

i'm not certain if its the correct way

It isn't. To give one counterexample, it thinks that 25 is a prime number. To make matters worse, there are infinitely many such counterexamples.

Wikipedia is worth of a read for various (correct) methods of doing this.

NPE
  • 438,426
  • 93
  • 887
  • 970
1

The Wikipedia article on primality can help you design a better algorithm. There are many of them, but the basic ones are not that complicated.

  • First, depart from the fact that a prime number must be a positive integer bigger than 1. This invariant implies that if n < 2 you could return false immediatelly. In your code, n=0 fails.
  • In a naive approach, you can then move to check all divisors of n from 1 to n. If you just find two, then you know it's a prime.
  • A more intuitive approach could be to conclude that every number is divisible by 1 and itself, and so, you could check for divisors only between 2 and n-1. And in the moment that you find a divisor of n, you can conclude n is not a prime.
  • A improved approach recognizes that all even numbers are divisible by 2, and so, if n is not divisible by 2 then, from there on you can only check for odd divisors.
  • Finally, you do not need to check for all the divisors up to n. It should suffice to check divisor up to the square root of n. If you haven't found a divisor when you reach that threshold, then you can conclude n is a prime.
Edwin Dalorzo
  • 70,022
  • 25
  • 131
  • 191