Ramanujan & Python

barnesc at engr.orst.edu barnesc at engr.orst.edu
Mon Sep 6 15:48:07 EDT 2004


A bit of fun:

Ramanujan, an Indian mathematician, was once visited in the hospital
by G. H. Hardy, a prominant English mathematician.  Hardy remarked
that he had taken taxi number 1729, and Ramanujan quickly replied
that 1729 is remarkable, as it is the smallest integer that can be
represented in two ways by the sum of two cubes: 1729 = 1**3 + 12**3
= 9**3 + 10**3 [1].

Spectacular, no?

The inspired reader checks this with a quick Python program:

>>> L = range(1,21)
>>> sums = [x**3+y**3 for x in L for y in L]
>>> histo = [sums.count(i) for i in range(max(sums)+1)]
>>> histo.index(4)
1729

Explanation:
20**3 is 8000, so our search extends only up to 8000.
sums contains x**3+y**3 values for each x in L for each y in L.
(note that 1**3 + 12**3 and 12**3 and 1**3 are counted twice in sums).
histo counts how many times each value appears in sums.

The point is that Python is great for mathematical experiments.

This particular program is inefficient on the histo= line, so if you
want to try other cases (such as smallest integer that can be
represented in two ways by the sum of two fourths), you'll need to
optimize.

[1]. http://scienceworld.wolfram.com/biography/Ramanujan.html

This document is in the public domain.

 - Connelly



More information about the Python-list mailing list