Python Program to Find All Pythagorean Triplets in the Range

This is a Python Program to determine all Pythagorean triplets till the upper limit.

Problem Description

The program takes a upper limit and determines all Pythagorean triplets till the upper limit.

Problem Solution

1. Take in the upper limit and store it in a variable.
2. Using a while loop and for loop, compute the Pythagorean triplets using the formula.
3. If the value of the c is greater than the upper limit or if any of the numbers is equal to 0, break from the loop.
4. Print all the three numbers of the Pythagorean triplets.
5. Exit.

Program/Source Code

Here is source code of the Python Program to determine all Pythagorean triplets till the upper limit. The program output is also shown below.

limit=int(input("Enter upper limit:"))
c=0
m=2
while(c<limit):
    for n in range(1,m+1):
        a=m*m-n*n
        b=2*m*n
        c=m*m+n*n
        if(c>limit):
            break
        if(a==0 or b==0 or c==0):
            break
        print(a,b,c)
    m=m+1
Program Explanation

1. User must enter the upper limit and store it in a variable.
2. The while and for loop is used to find the value of the Pythagorean triplets using the formula.
3. If the value of a side is greater than the upper limit or if any of the side is 0, the loop is broken out of.
4. Then the triplets are printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter upper limit:20
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20 
 
Case 2:
Enter upper limit:35
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Note: Join free Sanfoundry classes at Telegram or Youtube

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.