pythonintegerpythagorean

coprime integers and Pythagorean Triplets in python


I am new to Python. I was given a task with an example that looks like this. My task is to find another way to prove a, b, c are Coprime Integers and to calculate a Pythagorean Triplets with input c. Can anyone show me another way or similar to solve this problem?

c = int(input('c: ')) 
sol = 'No solution'

ab = True #Definition of ab
bc = True #Definition of bc
ac = True #Definition of ac

for b in range (3, c):
    for a in range (2, b):
        if (a**2 + b**2) / (c**2) == 1:
            for i in range (2, a+1):
                if b % i == 0 and a % i == 0: #Coprime integers a,b
                    ab = False
                    break
                else:
                    ab = True
            for j in range (2, b+1):
                if b % j == 0 and c % j == 0: #Coprime integers b,c
                    bc = False
                    break
                else:
                    bc = True
            for k in range (2, a+1):
                if a % k == 0 and c % k == 0: #Coprime integers a,c
                    ac = False
                    break
                else:
                    ac = True
                    
            if ab==True and bc==True and ac==True: #Coprime integers a,b,c
                sol = "%i^2 + %i^2 = %i^2" % (a,b,c) #output
print(sol)

The input should look like exp. c: 5 and output should be 3^2 + 4^2 = 5^2. Thanks in advance.


Solution

  • Your code can be cleaned up greatly with the Euclidean gcd function (two numbers are coprime if and only if their gcd is 1):

    from math import gcd
    
    c = int(input('c: '))
    
    found_sol = False
    
    for b in range(3, c):
        for a in range(2, b):
            if a**2 + b**2 == c**2:
                valid = True
                if gcd(a, b) != 1 or gcd(a, c) != 1 or gcd(b, c) != 1:
                    continue
                print(f"{a}^2 + {b}^2 = {c}^2")
                found_sol = True
    
    if not found_sol:
        print("No solution found.")
    

    Also, you know a must equal sqrt(c**2 - b**2), so you can save a loop:

    from math import sqrt, gcd
    
    c = int(input('c: '))
    
    found_sol = False
    
    def gcd(a, b):
        while b != 0:
            a, b = b, a % b
        return a
    
    for b in range(3, c):
        a = int(sqrt(c**2 - b**2))
        if a < b and a**2 + b**2 == c**2:
            valid = True
            if gcd(a, b) != 1 or gcd(a, c) != 1 or gcd(b, c) != 1:
                continue
            print(f"{a}^2 + {b}^2 = {c}^2")
            found_sol = True
    
    if not found_sol:
        print("No solution found.")