[Edu-sig] Opencourseware: Perfect Numbers with Generators

kirby urner kirby.urner at gmail.com
Mon Feb 19 02:26:10 CET 2007


Author:  Kirby Urner
Subjects: CS0, Pythonic Mathematics, Python for Math Teachers
Originating Academy:  Saturday Academy (saturdayacademy.org)
Originating Course:  Pythonic Mathematics: from Fibonaccis to Fractals
Major Reference:  http://www.4dsolutions.net/ocn/perfectnumbers.html

"""
Sequence generator expressions

Usage (one of many):

>>> from euclidix36 import mersennes, perfects
>>> perfects.next()
6
>>> perfects.next()
28
>>> perfects.next()
496
>>> perfects.next()
8128
>>> perfects.next()
33550336
>>> mersennes.next()
131071
>>> mersennes.next()
524287
>>> mersennes.next()
2147483647L

"""

# http://www.research.att.com/~njas/sequences/A000043
mersennep   = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89,
               107, 127, 521, 607, 1279, 2203, 2281,
               3217, 4253, 4423, 9689, 9941, 11213,
               19937, 21701, 23209, 44497, 86243,
               110503, 132049, 216091, 756839, 859433,
               1257787, 1398269, 2976221, 3021377,
               6972593, 13466917] # ...

# http://www.research.att.com/~njas/sequences/A000668
mersennes = (pow(2,p) - 1 for p in mersennep )

# http://www.research.att.com/~njas/sequences/A000396
perfects = (m*(m+1)//2 for m in mersennes)


"""
For discussion:

Explain why mersennes.next() doesn't return the first
Mersenne prime, when used after three invocations of
the perfects generator expression (see Usage above).

Answer: because the perfects generator expression has
already advanced the mersennes generator.

Is the converse of Euclid's IX:36 true, i.e. if a number
is perfect, then is it necessarily some Mth triangular
number, where M is a Mersenne prime?

Answer: only if the perfect number is even.  It's not
yet known if any perfects are odd:
http://primes.utm.edu/mersenne/index.html
http://mathworld.wolfram.com/OddPerfectNumber.html
"""


More information about the Edu-sig mailing list