TMTOWTDI, guy.
My way demonstrates how to use an else clause in conjunction with a for loop (yes, that is a for...else statement in my script, no mistake).
I saw your prime calculating program on CCAE. *Consider this one I made:
It seems to be much faster (not to mention more proper)Code:#!/usr/bin/env python import math, sys def isPrime(n, sqroot): *for x in xrange(2, sqroot+1): * *if n % x == 0: * * *return 0 *return 1 if len(sys.argv) < 2: *print "Usage: %s <Upper limit>" % sys.argv[0] *sys.exit(1) try: *number = int(sys.argv[1]) except ValueError: *print "The limit must be an integer" *sys.exit(1) sqroot = math.sqrt(number) for i in xrange(1, number+1, 2): *if isPrime(i, sqroot): print i
TMTOWTDI, guy.
My way demonstrates how to use an else clause in conjunction with a for loop (yes, that is a for...else statement in my script, no mistake).
For every iteration you calculate the square root. Check the difference:
Kindda faster, heh?./prime.py 10000 0.34s user 0.01s system 75% cpu 0.466 total
./feztaa.py 10000 5.45s user 0.04s system 55% cpu 9.896 total
That's odd vince, seeing as mine doesn't take commandline arguments. It's interactive. Anyway, I'll look into it. It's not a priority right now.
No need to look, I already said what was the problem: you calculate the square root way too often.
Bookmarks