pythagorean triples exercise

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


On Oct 22, 8:07 am, Dennis Lee Bieber <wlfr... at ix.netcom.com> wrote:
> On Thu, 21 Oct 2010 03:51:07 -0700 (PDT), Baba <raoul... at gmail.com>
> declaimed the following in gmane.comp.python.general:
>
> > Hi everyone
>
> > i need a hint regarding the following exercise question:
>
> > "Write a program that generates all Pythagorean triples whose small
> > sides are no larger than n.
> > Try it with n <= 200."
>
> > what is "n" ? i am guessing that it is a way to give a bound to the
> > triples to be returned but i can't figure out where to fit in "n".
>
> > a^a + b^b = c^c is the condition to satisfy and i need to use loops
>
>         Well, I'd interpret it to mean that
>
> a <= 200
> AND
> b <= 200
>
> since c is the hypotenuse, which by definition is longer than either of
> the sides.
>
>         The brute force approach is a nested set of "for" loops, running
> 1-200 (remember that (x)range(200) runs 0-199 <G>).
>
>         The alternative is to study the information at
>
> http://www.math.uic.edu/~fields/puzzle/triples.html
>
> and filtering out entries where the first two components are >200...
> Looking at the middle term "2*m*n" would have to be less than 201, and
> the first term "n*n-m*m" < 201
>
>         In Python, this can all be done in a one-liner...
>
> [(n*n - m*m, 2*m*n, n*n + m*m) for n in xrange(2,101) for m in
> xrange(1,n) if 2*m*n < 201 and n*n-m*m < 201]
>
>         Converting this to a clean set of nested loops and nice lines of
> output is a different matter.
>
>         Oh, and DO study the link I gave so you can cite it when you turn in
> this intriguing formulation... after all, no need for math.sqrt <G>
>
> --
>         Wulfraed                 Dennis Lee Bieber         AF6VN
>         wlfr... at ix.netcom.com    HTTP://wlfraed.home.netcom.com/

Hi Wulfraed,

only a has an upper limit of 200

the program needs to output the following triple for a == 200: (200 ,
609,641)

so at this stage my problem is: how to set the upper limit for b in a
smart way?

My solution below is not efficient i believe.

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



More information about the Python-list mailing list