Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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 <stdlib.h>
- #include <math.h>
- #include <vector>
- #include <algorithm>
- #define LIMITPERIMETER 1000
- using namespace std;
- int main()
- {
- // 1. First, I will create a vector, in which i will place the counter of solution of each perimeter
- // In index = 0 there will be the number of solutions when perimeter = 3 = min, in index = 1, the solutions of perimeter = 4, ....
- // Therefore, the length will be: length = LIMITPERIMETER - 3 + 1
- vector <int> counterOfPerimSolutions = vector <int> ();
- // Initialization of the vector
- for(int i=0; i<LIMITPERIMETER-3+1; i++){
- counterOfPerimSolutions.push_back(0);
- }
- // 2. I make 2 for-loops
- for(int a=1; a<=999; a++){
- for(int b=1; b<=999; b++){
- double c = sqrt(a*a + b*b);
- if(c == int(c) && a+b+c <= LIMITPERIMETER){
- // That means that a,b,c are integers, that create
- int perimeter = a + b + c;
- // This value is in index perimeters - 3 in the vector
- cout << "a = " << a << ", b = " << b << ", c = " << c << " ----> perimeter = " << perimeter << endl;
- counterOfPerimSolutions[perimeter-3]++;
- }
- }
- }
- /*
- for(int i=0; i<counterOfPerimSolutions.size(); i++){
- cout << counterOfPerimSolutions[i] << " sols for perim = " << i+3 << endl;
- }
- */
- // 3. Now, the vector contains all the solutions, but each solution is twice, because there are 2 different combinations of a and b (and therefore c), that lead to the same perimeter
- // For perimeter = 120, I can have a=30, b=40, c=50 and a=40, b=30, c=50, but that's the same solution
- for(unsigned int i=0; i<counterOfPerimSolutions.size(); i++){
- counterOfPerimSolutions[i] /= 2;
- }
- // 4. Find the perimeter, with the most solutions
- int maxIndex = 0;
- int maxSolutions = counterOfPerimSolutions[0];
- for(unsigned int i=1; i<counterOfPerimSolutions.size(); i++){
- if(counterOfPerimSolutions[i] > maxSolutions){
- maxSolutions = counterOfPerimSolutions[i];
- maxIndex = i;
- }
- }
- // 5. Now, I have the value of maxIndex. But this index is connected with a perimeter's value, especially the value: maxIndex + 3
- cout << "\nIn range: 3 <= perimeter <= " << LIMITPERIMETER << ", the max different solutions are " << counterOfPerimSolutions[maxIndex] << " and the value of this perimeter is " << maxIndex + 3 << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement