• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Find All Pythagorean Triples in a Range using Python

Find All Pythagorean Triples in a Range using Python

March 10, 2022 Leave a Comment

To get all Pythagorean triples up to a given number in Python, we can use a for loop and apply the Pythagorean triplet’s square sum connection.

def pythagorean_triples(num):
    triples = []
    c, m = 0, 2
    while c < num:
        for n in range(1, m):
            a = m * m - n * n
            b = 2 * m * n
            c = m * m + n * n
            if c > num:
                break
            triples.append([a, b, c])
        m = m + 1
    return triples

print(pythagorean_triples(25))

#Output:
[[3, 4, 5], [8, 6, 10], [5, 12, 13], [15, 8, 17], [12, 16, 20], [7, 24, 25]]

A less efficient solution for getting all Pythagorean triples in a range is checking all numbers in a range to see if a squared plus b squared equals c squared in a loop.

def pythagorean_triples(num):
    triples = []
    for b in range(1, num):
        for a in range(1, b):
            c = (a ** 2 + b ** 2) ** (1/2)
            if c % 1 == 0 and c <= num:
                triples.append([a, b, int(c)])
            elif c > num:
                break
    return triples

print(pythagorean_triples(25))

#Output:
[[3, 4, 5], [6, 8, 10], [5, 12, 13], [9, 12, 15], [8, 15, 17], [12, 16, 20], [15, 20, 25], [7, 24, 25]]

Python allows us to implement complex algorithms to do various calculations. One such calculation is finding all of the Pythagorean triples in a range of numbers.

Pythagorean triples are a set of three whole numbers where a squared plus b squared equals c squared.

We can find Pythagorean triples in a range easily by with a loop and apply the Pythagorean triplet’s square sum connection. The square sum connection gives us equations which can help us solve for a, b and c.

Below is an example in Python of how to get Pythagorean triples up to a given number.

def pythagorean_triples(num):
    triples = []
    c, m = 0, 2
    while c < num:
        for n in range(1, m):
            a = m * m - n * n
            b = 2 * m * n
            c = m * m + n * n
            if c > num:
                break
            triples.append([a, b, c])
        m = m + 1
    return triples

print(pythagorean_triples(25))

#Output:
[[3, 4, 5], [8, 6, 10], [5, 12, 13], [15, 8, 17], [12, 16, 20], [7, 24, 25]]

Getting the First n Pythagorean Triples in Python

If you want to get the first n Pythagorean triples, instead of finding the Pythagorean triples up to a certain number, we can easily change the function above.

Instead of checking if c is less than num, we will check the length of the triples list.

Below is how to get the first 5 Pythagorean triples in Python.

def pythagorean_triples(num):
    triples = []
    c, m = 0, 2
    while len(triples) < num:
        for n in range(1, m):
            a = m * m - n * n
            b = 2 * m * n
            c = m * m + n * n
            if len(triples) == num:
                break
            triples.append([a, b, c])
        m = m + 1
    return triples

print(pythagorean_triples(5))

#Output:
[[3, 4, 5], [8, 6, 10], [5, 12, 13], [15, 8, 17], [12, 16, 20]]

Brute Force Method for Computing Pythagorean Triples in Python

A less efficient solution for getting all Pythagorean triples in a range is checking all numbers in a range to see if a squared plus b squared equals c squared in a loop.

We can brute force all of the Pythagorean triples in a range by looping over all valid combinations of a and b and check if a squared plus b squared equals c squared.

Below is a simple example of a Python function which calculates Pythagorean triples up to a given number.

def pythagorean_triples(num):
    triples = []
    for b in range(1, num):
        for a in range(1, b):
            c = (a ** 2 + b ** 2) ** (1/2)
            if c % 1 == 0 and c <= num:
                triples.append([a, b, int(c)])
            elif c > num:
                break
    return triples

print(pythagorean_triples(25))

#Output:
[[3, 4, 5], [6, 8, 10], [5, 12, 13], [9, 12, 15], [8, 15, 17], [12, 16, 20], [15, 20, 25], [7, 24, 25]]

Hopefully this article has been useful for you to learn how to get Pythagorean triples in Python.

Other Articles You'll Also Like:

  • 1.  Find First Occurrence in String of Character or Substring in Python
  • 2.  Transpose DataFrame pandas – Using the pandas transpose Function
  • 3.  Check if pandas DataFrame is Empty in Python
  • 4.  Python Check if Dictionary Value is Empty
  • 5.  Break Out of Function in Python with return Statement
  • 6.  Drop Duplicates pandas – Remove Duplicate Rows in DataFrame
  • 7.  Remove Trailing Zeros from String with rstrip() in Python
  • 8.  Get Difference Between datetime Variables in Python
  • 9.  Python os.sep – Create Operating System Path Seperator Character
  • 10.  Python tostring method – Convert an Object to String with str() Function

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy