It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples. 12 cm: (3,4,5) 24 cm: (6,8,10) 30 cm: (5,12,13) 36 cm: (9,12,15) 40 cm: (8,15,17) 48 cm: (12,16,20) In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles. 120 cm: (30,40,50), (20,48,52), (24,45,51) Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed?
I use Euclid's formula to generate Pythagorean triples, which states the integers \( a = m^2 - n^2 ,\ \, b = 2mn ,\ \, c = m^2 + n^2 \)
form a Pythagorean triple.
By inserting an additional parameter k to the formula, we can generate many Pythagorean triples uniquely:
\( a = k\cdot(m^2 - n^2) ,\ \, b = k\cdot(2mn) ,\ \, c = k\cdot(m^2 + n^2) \)
This feature was used to optimize the calculation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include<iostream> #include<cmath> using std::cout; using std::endl; int gcd(int a, int b); int main() { const int L = 1500000; int M = sqrt(L/2); int tris[L+1] = { 0 }; for (int m = 2; m < M; m++) { for (int n = 1; n < m; n++) { if ( (m+n) % 2 == 1 && gcd(m,n) == 1) { int p = 2*m*(m+n); for ( int k = 1; k <= L/p; k++) tris[k*p]++; } } } int cnt = 0; for (int i=1; i <= L; i++) { if (tris[i] == 1) cnt++; } cout << "Answer of PE 75 is: " << cnt << endl; } int gcd( int a, int b ) { if ( a == 1 || b == 1 ) return 1; if ( a == 0 || b == 0 ) return ( a + b ); return gcd( b, a % b ); } |
> system.time(system("./pe75")) Answer of PE 75 is: 161667 user system elapsed 0.058 0.004 0.066