Saturday, 18 November 2023

Write a program to generate all Pythagorean Triplets with side length less than or equal to 50.

 Certainly! Let me explain the code step by step:

# Function to check if a, b, c form a Pythagorean triplet

def is_pythagorean_triplet(a, b, c):

    return a**2 + b**2 == c**2

This part defines a function is_pythagorean_triplet that takes three arguments (a, b, and c) and returns True if they form a Pythagorean triplet (satisfy the Pythagorean theorem), and False otherwise.

# Generate and print all Pythagorean triplets with side lengths <= 50

for a in range(1, 51):

    for b in range(a, 51):

Here, two nested for loops are used. The outer loop iterates over values of a from 1 to 50. The inner loop iterates over values of b from a to 50. The inner loop starts from a to avoid duplicate triplets (e.g., (3, 4, 5) and (4, 3, 5) are considered duplicates).

        c = (a**2 + b**2)**0.5  # Calculate c using the Pythagorean theorem

        if c.is_integer() and c <= 50:

            print(f"Pythagorean Triplet: ({a}, {b}, {int(c)})")

Within the loops, the program calculates the value of c using the Pythagorean theorem (c = sqrt(a^2 + b^2)). The is_integer() method is then used to check if c is a whole number. If it is, and if c is less than or equal to 50, the triplet (a, b, c) is printed as a Pythagorean triplet.


# Function to check if a, b, c form a Pythagorean triplet

def is_pythagorean_triplet(a, b, c):

    return a**2 + b**2 == c**2


# Generate and print all Pythagorean triplets with side lengths <= 50

for a in range(1, 51):

    for b in range(a, 51):

        c = (a**2 + b**2)**0.5  # Calculate c using the Pythagorean theorem

        if c.is_integer() and c <= 50:

            print(f"Pythagorean Triplet: ({a}, {b}, {int(c)})")


0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (49) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (929) Python Coding Challenge (354) Python Quiz (22) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses