pythagorean triples exercise

Terry Reedy tjreedy at udel.edu
Fri Oct 22 01:35:11 EDT 2010


On 10/21/2010 7:55 PM, Baba wrote:

> the bit i'm having difficulties with in constructing my loops is:
> "whose small sides are no larger than n"

from math import sqrt

def py_trips(n):
   for b in range(4,n+1):
     for a in range(3,b+1):
       cf = sqrt(a*a+b*b)
       c  = int(cf)
       if c == cf: yield a, b, c

for t in py_trips(200): print(t)

# prints
(3,4,5)
...
(150, 200, 250)

This version assumes that if a*a+b*c is an exact square of an integer, 
the floating point sqrt will be an exact integral value, which I believe 
it should be for values up to the max (for n max 200) of 80000.

It produces multiples of each triple, such as (3,4,5), (6,8,10), 
(9,12,15), ... (150,200, 250), which a different formulation of the 
problem might exclude, to only ask for 'basic' triples of relatively 
prime numbers.



-- 
Terry Jan Reedy




More information about the Python-list mailing list