def find_pythagorean_triplets(limit):
triplets = []
for a in range(1, limit + 1):
for b in range(a, limit + 1):
for c in range(b, limit + 1):
if a**2 + b**2 == c**2:
triplets.append((a, b, c))
return triplets
limit = int(input("Enter the range limit: "))
triplets = find_pythagorean_triplets(limit)
print("Pythagorean Triplets in the range 1 to", limit, "are:")
for triplet in triplets:
print(triplet)
#source code --> clcoding.com
Code Explanation:
1.Function:
find_pythagorean_triplets(limit)
Purpose:
To find all the Pythagorean triplets for numbers in the range 1 to limit.
How it works:
It initializes an empty list triplets to store valid triplets.
It uses three nested for loops to iterate through all possible values of a, b, and c such that:
a starts from 1 and goes up to limit.
b starts from a (to avoid duplicate combinations like (3,4,5) and (4,3,5)) and goes up to limit.
c starts from b (ensuring a <= b <= c to maintain order) and also goes up to limit.
If the condition is true, the triplet (a, b, c) is added to the triplets list.
Finally, the list of valid triplets is returned.
2. Input:
The user is asked to enter a positive integer limit using input(). This defines the upper range for a, b, and c.
3. Output:
The function find_pythagorean_triplets(limit) is called with the input range.
It prints all valid Pythagorean triplets found within the range 1 to limit.
Example Execution:
Input:
Enter the range limit: 20
Output:
Pythagorean Triplets in the range 1 to 20 are:
(3, 4, 5)
(5, 12, 13)
(6, 8, 10)
(8, 15, 17)
(9, 12, 15)
(12, 16, 20)
0 Comments:
Post a Comment