Filtered out even numbers, except number 2, to speed things up.
vegaseat
DaniWeb's Hypocrite
6,464 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,607
Skill Endorsements: 34
Gribouillis
Posting Maven
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 760
Skill Endorsements: 11
gmorcan,
using Python modue timeit and a rather small prime number like 999979, your function is 2700 times slower than vegaseat's function.
Lardmeister
Posting Virtuoso
1,938 posts since Mar 2007
Reputation Points: 465
Solved Threads: 72
Skill Endorsements: 5
OK, here is a really optimized version for this classic problem. This is not originally mine (but have done very similar).
It utilizes the fact that primes > 4 are 1(mod 6) or 5(mod 6). Actually I editted it a lot now before posting to be more according to format standards of PEP8.
def is_prime(n):
if n == 2 or n == 3:
return True
elif n < 2 or n % 2 == 0:
return False
elif n < 9:
return True
elif n % 3 == 0:
return False
r = int(sqrt(n))
f = 5
while f <= r:
if n % f == 0 or n % (f + 2) == 0:
return False
else:
f += 6
return True
pyTony
pyMod
6,299 posts since Apr 2010
Reputation Points: 879
Solved Threads: 984
Skill Endorsements: 26
Real hack, and surely stupendously inefficient. Best as joke or concept. Do not try to test (2**13-1) with it.
pyTony
pyMod
6,299 posts since Apr 2010
Reputation Points: 879
Solved Threads: 984
Skill Endorsements: 26
You have made the classic mistake of including even numbers = testing twice as many numbers. Start out with i=3 and add two on each pass.
woooee
Posting Maven
2,703 posts since Dec 2006
Reputation Points: 827
Solved Threads: 777
Skill Endorsements: 9
People seem to think it's a violation of some natural law if a beginner programmer joins a discussion and tries to make a positive contribution by posting code.
On the contrary, we answer beginner programmer's questions every day in the python forum and try to help them as much as we can. Correct errors and inefficiencies in code is not rude or socially inept: we all learn by our own mistakes.
I would advise beginner programmers to start their own thread with well described issues to solve. They will probably get better answers than by adding to a code snippet thread.
They may also find many ideas in Vegaseat's thread projects-for-the-beginner.
Gribouillis
Posting Maven
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 760
Skill Endorsements: 11