reportsuf.blogg.se

Prime number generator algorithm python
Prime number generator algorithm python









prime number generator algorithm python

Since zero is false, I suppose the "!= 0" parts could be omitted from the conditionals, but I think it's easier to read with them in. To do so I wrote a generator for prime numbers: def primes (): x 2 while True: for y in xrange (2, x/2 + 1): if x y 0: break else: yield x x x + 1. The integer division used to calculate m will have to be changed for Python 3. I'm trying to get a better grasp on generators in Python because I don't use them enough (I think generators are cool). m is a little tricky it's the number of multiples of i that are greater than i**2 and less than or equal to n.

prime number generator algorithm python prime number generator algorithm python

The three terms that define the slice are the same as the three terms that define the range for j in the "Alex" code, which is why I think the code is still readable. So according to the results, it seems possible to generate a list of only prime numbers by calculating f2(k+s) into a specific range of K1.k and finding the. The slice assignment seems to be the big time saver. The code below runs about 50% faster than the "Alex" code and isn't too obscure, I think: nroot = int(sqrt(n)) Twice as fast? In my benchmarks (on an Intel iMac with n=1,000,000, n=10,000,000, and n=20,000,000), the recipe code is only about 10% faster than the "Alex" code, although its memory use is probably much smaller. Essentially I would like to automate the process that is being shown in my code so it can work for any range and all prime numbers.Def primes ( n ): if n = 2 : return elif n < 2 : return s = range ( 3, n + 1, 2 ) mroot = n ** 0.5 half = ( n + 1 ) / 2 - 1 i = 0 m = 3 while m <= mroot : if s : j = ( m * m - 3 ) / 2 s = 0 while j < half : s = 0 j += m i = i + 1 m = 2 * i + 3 return + print primes ( 13 ) print primes ( 3000 ) - we get. My code is very long and redundant but I know it can definitely be condensed and made less repetitive with a few changes and I was hoping I could be pointed in the right direction. I see that there are many different ways to generate prime numbers.











Prime number generator algorithm python