Python Prime Number Checker

For the discussion of Perl, Python, Ruby, and PHP and other interpreted languages.

Python Prime Number Checker

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Last edited by Arrexel on Sat May 26, 2018 2:59 pm, edited 1 time in total.
"I think there is a world market for maybe five computers."
Unverified Quote, 1945 - Thomas J. Watson, Founder of IBM

Arrexel
New User

Posts: 31
Joined: Fri Feb 13, 2009 7:44 pm
Blog: View Blog (0)

Re: Python Prime Number Checker

I'm not much of a coder but from a mathematical point of view, it would be quicker to use the square root function instead of the primehalf that you use. Also you can check for divisibility by 2 in a seperate step, then set your divisor=3 at the start and increase by 2 instead (since you only need to check the odd numbers).

Code: Select all
`# Prime Number Checker by Alex "Arrexel" Reidprint "Prime Number Checker"primenum = float(raw_input("Enter the number to check: "))if primenum % 2 == 0:      print int(primenum), "is not a prime number."primeroot=int(primenum**.5)divisor = 3prime = Truefor x in range(primeroot):    if primenum % divisor == 0:        print int(primenum), "is not a prime number."        prime = False        break    divisor += 2if prime != False:    print int(primenum), "is a prime number."`

Hopefully this helps!
Gangees
New User

Posts: 1
Joined: Sun Feb 22, 2009 7:09 pm
Blog: View Blog (0)

Re: Python Prime Number Checker

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Last edited by Arrexel on Sat May 26, 2018 2:59 pm, edited 1 time in total.
"I think there is a world market for maybe five computers."
Unverified Quote, 1945 - Thomas J. Watson, Founder of IBM

Arrexel
New User

Posts: 31
Joined: Fri Feb 13, 2009 7:44 pm
Blog: View Blog (0)

Re: Python Prime Number Checker

You can optimize it even further by pregenerating a list of prime numbers, and only checking if the input is divisible by prime numbers.

TheMindRapist
Contributor

Posts: 585
Joined: Mon Apr 14, 2008 4:57 pm
Blog: View Blog (0)

Re: Python Prime Number Checker

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Last edited by Arrexel on Sat May 26, 2018 2:59 pm, edited 1 time in total.
"I think there is a world market for maybe five computers."
Unverified Quote, 1945 - Thomas J. Watson, Founder of IBM

Arrexel
New User

Posts: 31
Joined: Fri Feb 13, 2009 7:44 pm
Blog: View Blog (0)

Re: Python Prime Number Checker

Yeah, like TheMindRapist said you could have a list of primes and check against that list. Maybe something like this which could be expanded on with some 'if' statements but you get the idea:

>>> primes=[2,3,5,7,11,13,17,19,23]
>>> str_digits="23"
>>> str_prime=''.join([c for c in str_digits if int(c) in (primes)])
>>> str_prime
'23'

Defience