Special Pythagorean triplet
Problem 9
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
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.
Problem 9 is about Pythagorean triplet.
The basic formula is :
A2 + B2 = C2
Using this formula will easily solve the problem.
One quick trick is to set the limit to int A and B so that we can reduce the time.
Assuming that B is always greater than or equal to A, B will always start with A.
Also, A will be less than one third of the perimeter since A is the smallest side of a triangle.
B will be less than one half of the perimeter since B should be smaller than the hypotenuse, C.
for (int a=1, end = 1000/3; a < end; a++) { for (int b=a, end2 = 1000/2; b < end2; b++) { int c = 1000-a-b; if (c>0 && a*a + b*b == c*c) { System.out.println(a*b*c); return; } } }
Execution time is 1.7 ms, or 0.0017 seconds
No comments:
Post a Comment