1. 程式人生 > >Project Euler Problem 39

Project Euler Problem 39

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?

#include <iostream>
#include <ctime> 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, 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() { clock_t start = clock(); 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; clock_t finish = clock(); double duration = (double)(finish - start) / CLOCKS_PER_SEC; cout << "C/C++ application running time: " << duration << " seconds" << endl; return 0; }