Generator function for prime numbers [duplicate]

2024/11/14 18:24:13

I'm trying to write a generator function for printing prime numbers as follows

 def getPrimes(n):prime=Truei=2while(i<n):for a in range(2,i):if(i%a==0):prime=Falsebreakif(prime):    yield i

However I'm not getting the desired results p=getPrimes(100) should give me a generator function that will iterate primes from 2 through 100 but the result I'm getting is [2,3]. What am I doing wrong?

Answer

Sieve of Eratosthenes: Most efficient prime generator algorithm

Taken from here:

Simple Prime Generator in Python - an answer by Eli Bendersky.

enter image description here

It marks off all the multiples of 2, 3, 5, 7 and 11. The rest are all prime numbers.

def genprimes(limit): # derived from # Code by David Eppstein, UC Irvine, 28 Feb 2002D = {}            # http://code.activestate.com/recipes/117119/q = 2while q <= limit:if q not in D:yield qD[q * q] = [q]else:for p in D[q]:D.setdefault(p + q, []).append(p)del D[q]q += 1p = genprimes(100)
prms = [i for i in p]print prms

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
https://en.xdnf.cn/q/71924.html

Related Q&A

`ValueError: too many values to unpack (expected 4)` with `scipy.stats.linregress`

I know that this error message (ValueError: too many values to unpack (expected 4)) appears when more variables are set to values than a function returns. scipy.stats.linregress returns 5 values accord…

Django prefetch_related from foreignkey with manytomanyfield not working

For example, in Django 1.8:class A(models.Model):x = models.BooleanField(default=True)class B(models.Model):y = models.ManyToManyField(A)class C(models.Model):z = models.ForeignKey(A)In this scenario, …

Running SimpleXMLRPCServer in separate thread and shutting down

I have a class that I wish to test via SimpleXMLRPCServer in python. The way I have my unit test set up is that I create a new thread, and start SimpleXMLRPCServer in that. Then I run all the test, and…

Clean Python multiprocess termination dependant on an exit flag

I am attempting to create a program using multiple processes and I would like to cleanly terminate all the spawned processes if errors occur. below Ive wrote out some pseudo type code for what I think …

Any limitations on platform constraints for wheels on PyPI?

Are there any limitations declared anywhere (PEPs or elsewhere) about how broad a scope the Linux wheels uploaded to PyPI should have? Specifically: is it considered acceptable practice to upload li…

Match set of dictionaries. Most elegant solution. Python

Given two lists of dictionaries, new one and old one. Dictionaries represent the same objects in both lists. I need to find differences and produce new list of dictionaries where will be objects from n…

Cookies using Python and Google App Engine

Im developing an app on the Google App Engine and have run into a problem. I want to add a cookie to each user session so that I will be able to differentiate amongst the current users. I want them all…

Matplotlib animations - how to export them to a format to use in a presentation?

So, I learned how to make cute little animations in matplotlib. For example, this:import numpy as np import matplotlib import matplotlib.pyplot as pltplt.ion()fig = plt.figure() ax = fig.add_subplot(…

Where is python interpreter located in virtualenv?

Where is python intrepreter located in virtual environment ? I am making a GUI project and I stuck while finding the python interpreter in my virtual environment.

Tkinter check which Entry last had focus

I am working on a program that has a virtual keyboard I created using Tkinter. The pages that have the keyboard enabled have entry widgets where the users need to input data. I am using pyautogui as …