Python Program to Find Pythagorean Triplets
Intermediate · Numbers
A Pythagorean triplet is a set of three whole numbers a, b and c where a^2 + b^2 = c^2, such as 3, 4 and 5 (9 + 16 = 25). They are the sides of right-angled triangles, and this program finds every triplet whose sides are no bigger than a limit.
Program
Pythagorean triplets with sides up to 30: 3^2 + 4^2 = 5^2 (9 + 16 = 25) 5^2 + 12^2 = 13^2 (25 + 144 = 169) 6^2 + 8^2 = 10^2 (36 + 64 = 100) 7^2 + 24^2 = 25^2 (49 + 576 = 625) 8^2 + 15^2 = 17^2 (64 + 225 = 289) 9^2 + 12^2 = 15^2 (81 + 144 = 225) 10^2 + 24^2 = 26^2 (100 + 576 = 676) 12^2 + 16^2 = 20^2 (144 + 256 = 400) 15^2 + 20^2 = 25^2 (225 + 400 = 625) 18^2 + 24^2 = 30^2 (324 + 576 = 900) 20^2 + 21^2 = 29^2 (400 + 441 = 841) Triplets found: 11
How it works
- The two loops try every pair of sides
aandb, withbnever smaller thanaso each triplet appears only once. - For each pair,
a * a + b * bis the value thatc * cwould need to be. math.isqrt()gives the whole-number square root, and squaring it again shows whether the value really is a perfect square.- If it is, and
cis within the limit, the three numbers form a triplet and are printed with the working.
Other ways to write it
Euclid's formula
Primitive triplets from Euclid's formula: m=2, n=1: (3, 4, 5) m=3, n=2: (5, 12, 13) m=4, n=1: (15, 8, 17) m=4, n=3: (7, 24, 25) m=5, n=2: (21, 20, 29) m=5, n=4: (9, 40, 41)
Euclid's formula builds triplets directly instead of searching. These are the primitive ones, with no common factor; multiplying one by 2, 3 and so on gives the rest, like 6, 8, 10.
Checking three given numbers
(3, 4, 5) is a triplet (13, 5, 12) is a triplet (2, 3, 4) is not a triplet
Sorting first means the numbers can be given in any order, and *sides passes the three values in a tuple as three separate arguments.
Try it yourself
Find the one triplet whose sides add up to exactly 1000, a well-known Project Euler puzzle.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Find the Distance Between Two Points
- Check if a Number Is a Perfect Square
- Check Whether a Triangle Is Equilateral, Isosceles or Scalene
- Find the Square Root of a Number
- Check a Perfect Number
- Check an Armstrong Number
- Check a Palindrome Number
- Check a Prime Number
- Print the Fibonacci Series
- Find the GCD and LCM of Two Numbers
All Python programs · CBSE class 12 practical file · Python exercises