M H
M H

Reputation: 842

Pythagorean triple with python

I want to get a number 'n' and produce Pythagorean triple that total of them is equal with 'n'.

for example for n=12 my output is 3, 4, 5 (12 = 3 + 4 + 5).

I write below code but it take a lot of time for big numbers. please help me to improve it.

a = int(input())
done = False
for i in range(int(a/4)+1,2,-1):
    if done:
        break
    for j in range(i+1,int(a/2)+1):
        k = a-(i+j)
        if k <= j:
            break
        if i**2 + j**2 == k**2:
            print(i,j,k)
            done = True
            break
if done == False:
    print('Impossible')

Upvotes: 1

Views: 1361

Answers (3)

ParthS007
ParthS007

Reputation: 2689

To generate a Pythagorean triplet of a given sum, you can run two loops, where the first loop runs from i = 1 to n/3, the second loop runs from j = i+1 to n/2. In second loop, we check if (n – i – j) is equal to i * i + j * j.

n = int(input()
for i in range(1, int(n / 3) + 1): 
    for j in range(i + 1, int(n / 2) + 1): 
        k = n - i - j 
        if (i * i + j * j == k * k): 
            print(i, j, k) 

Upvotes: 0

MShakeG
MShakeG

Reputation: 613

I've used the joblib module to parallelize your code, though I haven't tested if there is a speedup for very large n; let me know:

from joblib import Parallel, delayed

done = False

def triple(a):
    global done 
    for i in range(int(a/4)+1,2,-1):
        if done:
            break
        for j in range(i+1,int(a/2)+1):
            k = a-(i+j)
            if k <= j:
                break
            if i**2 + j**2 == k**2:
                print(i,j,k)
                done = True
                break

    if done == False:
        print('Impossible')


if __name__ == '__main__':
    a = int(input("n:"))
    Parallel(n_jobs=-1, backend="threading")(map(delayed(triple),  [a])) 

Upvotes: 0

FAHAD SIDDIQUI
FAHAD SIDDIQUI

Reputation: 641

This code may help you

limits = int(input())
c, m = 0, 2

# Limiting c would limit  
# all a, b and c 
while c < limits : 

    # Now loop on n from 1 to m-1 
    for n in range(1, m) : 
        a = m * m - n * n 
        b = 2 * m * n 
        c = m * m + n * n 

        # if c is greater than 
        # limit then break it 
        if c > limits : 
            break

        if a+b+c == limits:
            print(a, b, c) 

    m = m + 1

>> 12
>> 3 4 5

Upvotes: 1

Related Questions