Problem 39 : Integer right triangles
If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.
{20,48,52}, {24,45,51}, {30,40,50}
For which value of p ≤ 1000, is the number of solutions maximised?
C++ source code
#include <iostream>
using namespace std;
class PE0039
{
private:
bool checkRightAngleTriangle(int a, int b, int c);
public:
int getMaxNumberOfSolutions(int &max_p);
};
bool PE0039::checkRightAngleTriangle(int a, int b, int c)
{
if (a*a + b*b == c*c) // a<c and b<c
{
return true;
}
return false;
}
int PE0039::getMaxNumberOfSolutions(int &max_p)
{
int max_number = 0;
for (int p=120; p<=1000; p++)
{
int number = 0;
for(int a=1; a<p/3; a++) // a+b+c=p => p>3a
{
for(int b=a; b<(p-a)/2; b++) // a<=b && b<p-a-b
{
if (true == checkRightAngleTriangle(a, b, p-a-b))
{
#ifdef UNIT_TEST
cout << "{" << a << ", " << b << ", " << p-a-b << " )"<<endl;
#endif
number++;
}
}
}
if (number > max_number)
{
max_number = number;
max_p = p;
}
}
return max_number;
}
int main()
{
PE0039 pe0039;
int max_p = 1;
int max_number = pe0039.getMaxNumberOfSolutions(max_p);
cout << max_p << " is the number of solutions maximised (";
cout << max_number << ")." << endl;
return 0;
}
Python source code
def getNumPOfMaxSolutions(max_perimeter):
"""
find the number p which has max number of solutions
"""
numOfSolutions_max, p_max = 0, 0
# perimeter p must be even because p=a+b+c and a*a + b*b = c*c
for p in range(120, max_perimeter+1, 2):
numOfSolutions = 0
# we suppose: a<=b, a<c, b<c, so
# a <= b = p*(p-2*a)/(2*(p-a)) => a <= p/(2+2**0.5)
for a in range(2, 1+int(p/(2+2**0.5))):
# a*a + b*b = c*c = (p-a-b)*(p-a-b) => b = p*(p-2*a)/(2*(p-a))
if p*(p-2*a)%(2*(p-a)) == 0:
numOfSolutions += 1
if numOfSolutions > numOfSolutions_max:
numOfSolutions_max, p_max = numOfSolutions, p
print("For p <=",max_perimeter,", number",p_max,\
"has max solutions(",numOfSolutions_max,").")
def main():
getNumPOfMaxSolutions(1000)
if __name__ == '__main__':
main()