Minority Opinions

Not everyone can be mainstream, after all.

Python Pythagorean Triple Generator

leave a comment »

For some crazy reason, I have spent significant amounts of time rediscovering a method of generating all possible primitive Pythagorean triples. After proving that the following works, I decided to check Wikipedia. Oh, well.

def rationals():
    x,y = 1,1
    while True:
        yield x,y
        x,y = y, (2*(x//y) + 1)*y - x

def odds():
    for x,y in rationals():
        if x % 2:
            yield x,y

def triplets():
    for x,y in odds():
        r,s,t = x**2, 2*x*y, 2*y**2
        yield r+s, s+t, r+s+t

if __name__ == "__main__":
    for trip in triplets():
        print trip
Advertisement

Written by eswald

25 Feb 2010 at 10:24 am

Posted in Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.