Special Pythagorean triplet

Problem 9

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Ans:-31875000

Code:-

n = 1000
m = -1
for a in range(3, (n//3)+1):
    b = (n**2 - 2*a*n)//(2*n - 2*a)
    c = n - b - a
    if a**2 + b **2 == c**2:
         if a*b*c > m:
            m = a*b*c
print(m)

programming Version Of This from Hackerrank.com

A Pythagorean triplet is a set of three natural numbers,a<b<c , for which,

a2+b2=c2

For example, 32+42=9+16=25=52

Given N , Check if there exists any Pythagorean triplet for which  a+b+c=N
Find maximum possible value of abc among all such Pythagorean triplets, If there is no such Pythagorean triplet print -1

Input Format

The first line contains an integer T i.e. number of test cases.
The next T lines will contain an integer N.

Constraints

  • 1⩽T⩽ 3000
  • 1⩽N⩽ 3000

Output Format

Print the value corresponding to each test case in separate lines.

Sample Input 

2
12
4

 

Sample Output 

60
-1

 

Explanation 0

  • For N=12, we have a triplet {3,4,5} , whose product is 60 .
  • For N=4, we don’t have any pythagorean triple.

Code:-

t = int(input().strip())
for a0 in range(t):
    n = int(input().strip())
    m = -1
    for a in range(3, (n//3)+1):
        b = (n**2 - 2*a*n)//(2*n - 2*a)
        c = n - b - a
        if a**2 + b **2 == c**2:
            if a*b*c > m:
                m = a*b*c
    print(m)