Python Program to Determine all Pythagorean Triplets in the Range

A Pythagorean triplet is a set of three positive integers a, b, c, such that a² + b² = c². The most famous example is 3, 4, 5 because 3² + 4² = 5² (9 + 16 = 25). This program finds all Pythagorean triplets where the hypotenuse c is within a given range.

Understanding Pythagorean Triplets

Pythagorean triplets can be generated using Euclid's formula:

  • a = m² - n²
  • b = 2mn
  • c = m² + n²

Where m > n > 0, and m and n are coprime integers.

Example

Here's a program to find all Pythagorean triplets within a specified range:

def pythagorean_triplets(limits):
    c, m = 0, 2
    while c < limits:
        for n in range(1, m):
            a = m * m - n * n
            b = 2 * m * n
            c = m * m + n * n
            if c > limits:
                break
            print(a, b, c)
        m = m + 1

upper_limit = 15
print("The upper limit is:")
print(upper_limit)
print("The Pythagorean triplets are:")
pythagorean_triplets(upper_limit)

Output

The upper limit is:
15
The Pythagorean triplets are:
3 4 5
8 6 10
5 12 13

How It Works

The algorithm uses Euclid's formula to generate primitive Pythagorean triplets:

  1. Start with m = 2 and iterate through values of n from 1 to m-1
  2. Calculate a, b, c using the formulas: a = m² - n², b = 2mn, c = m² + n²
  3. If c exceeds the limit, break the inner loop
  4. Otherwise, print the triplet and continue
  5. Increment m and repeat until c reaches the limit

Verification Example

Let's verify one of the triplets manually:

# Verify the triplet (3, 4, 5)
a, b, c = 3, 4, 5
print(f"a² + b² = {a}² + {b}² = {a**2} + {b**2} = {a**2 + b**2}")
print(f"c² = {c}² = {c**2}")
print(f"Is {a**2 + b**2} = {c**2}? {a**2 + b**2 == c**2}")
a² + b² = 3² + 4² = 9 + 16 = 25
c² = 5² = 25
Is 25 = 25? True

Alternative Approach with Different Range

Here's the same program with a larger range to see more triplets:

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

upper_limit = 30
triplets = pythagorean_triplets(upper_limit)
print(f"Found {len(triplets)} Pythagorean triplets with c ? {upper_limit}:")
for triplet in triplets:
    print(f"{triplet[0]}, {triplet[1]}, {triplet[2]}")
Found 5 Pythagorean triplets with c ? 30:
3, 4, 5
8, 6, 10
5, 12, 13
15, 8, 17
7, 24, 25

Conclusion

This program efficiently finds Pythagorean triplets using Euclid's formula within a given range. The method generates primitive triplets by systematically varying m and n parameters, making it suitable for finding all triplets up to a specified limit.

Updated on: 2026-03-25T19:20:33+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements