pythagorean triples exercise

Baba raoulbia at gmail.com
Fri Oct 22 08:39:45 EDT 2010


On Oct 22, 6:35 am, Terry Reedy <tjre... at udel.edu> wrote:
> 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

Hi Terry

Only a has an upper limit of 200. The exercise is n ot clar about that
i agree but assuming i am correct my program would need to be able to
generate the following triple: (200 ,609,641 )

My code below does that now but i think the way i compute b's upper
limit is not efficient.

import math
for a in range (1,200):
    for b in range (a,200):
        csqrd = a * a + b * b
        c = math.sqrt(csqrd)
        if math.floor(c) == c:
                print (a,b,int(c))

thanks
Baba



More information about the Python-list mailing list