find all multiplicands and multipliers for a number

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Apr 14 15:30:01 CEST 2015

```On Tue, 14 Apr 2015 08:35 pm, Rustom Mody wrote:

> On Tuesday, April 14, 2015 at 8:12:17 AM UTC+5:30, Paul Rubin wrote:
>> Steven D'Aprano  writes:
>> >
http://code.activestate.com/recipes/577821-integer-square-root-function/
>>
>> The methods there are more "mathematical" but probably slower than what
>> I posted.
>>
>> Just for laughs, this prints the first 20 primes using Python 3's
>> "yield from":
>>
>>     import itertools
>>
>>     def sieve(ps):
>>         p = ps.__next__()
>>         yield p
>>         yield from sieve(a for a in ps if a % p != 0)
>>
>>     primes = sieve(itertools.count(2))
>>     print(list(itertools.islice(primes,20)))
>>
>> It's not that practical above a few hundred primes, probably.
>
> Upto 490 its instantaneous

Not really instantaneous.

py> with Stopwatch():
...     x = list(itertools.islice(sieve(itertools.count(2)), 499))
...
time taken: 0.086171 seconds
py> from pyprimes import primes
py> with Stopwatch():
...     y = list(itertools.islice(primes(), 499))
...
time taken: 0.002802 seconds
py> x == y
True

I have to admit, I expected it to be significantly slower than it actually
is. Just goes to show, I've been using Python for 15+ years and my
intuition as to what is fast and what is slow is still mediocre at best.

Any beginner who thinks they can optimize code without measuring it first is
deluding themselves.

--
Steven

```

More information about the Python-list mailing list