[Tutor] Generate Prime Numbers
Alan Gauld
alan.gauld at btinternet.com
Fri May 29 19:48:38 CEST 2015
On 29/05/15 16:28, Mirage Web Studio wrote:
> Below is a sample code i created.
>
> Can i better it any way?
Of course. There is always improvements that can be made.
But in your case there are quite a few!
> def IsDivisibleBy3(number):#string variable
> v=0
> for c in number:
> v=v+int(c)
> if v%3==0:
> return True
> else:
> return False
def IsDivisibleBy3(number):#string variable
return not int(number) % 3
> def IsDivisibleBy7(number):#string variable
See above, but maybe better still
def isDivisibleByN(number, N):
return not int(number)%N
> def IsPrime(number):
Google for the "sieve of eratosthenes"
Or look it up on wikipedia.
That will give one of several possible
improvements to your algorithm.
> primelist=[]
>
> for i in range (11,200000,2):
> number=str(i)
> print "checking ",i
>
> if IsPrime(number):
Note, you are starting with a number, then converting
it to a string then in your functions converting it
back to a number.
That's crazy!
Also where do you store the primes less than 11?
ie. 1,3,5,7
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list