Anonymous user
Pythagorean triples/Java/Brute force primitives: Difference between revisions
Pythagorean triples/Java/Brute force primitives (view source)
Revision as of 16:57, 19 December 2011
, 12 years agoIt turns out that the GCD check can speed it up a little bit
(This is what I was really looking for when I made that last optimization) |
m (It turns out that the GCD check can speed it up a little bit) |
||
Line 1:
{{works with|Java|1.5+}}
This version brute forces primitive triple candidates and then scales them to find the rest (under the perimeter limit of course). Since it only finds the primitives mathematically it can optimize its candidates based on some of the properties [[wp:Pythagorean_triple#Elementary_properties_of_primitive_Pythagorean_triples|here]] -- namely that a and b have opposite evenness, only one of a and b is divisible by 3, only one of a and b is divisible by 4, c is always odd, and that a<sup>2</sup> + b<sup>2</sup> must be a perfect square (which [[wp:Square_number#Properties|don't ever end in 2, 3, 7, or 8]]).
It defines a <code>Triple</code> class which is comparable so it can be placed in a <code>
Note: this implementation also keeps all triples in memory. Be mindful of large perimeter limits.
Line 11:
import static java.math.BigInteger.*;
public class
public static final BigInteger TWO = BigInteger.valueOf(2),
B3 = BigInteger.valueOf(3),
Line 94:
(aabb.and(B127).intValue() != 16) &&
(aabb.and(B191).intValue() != 0)) continue;
if(!a.gcd(b).equals(ONE)) continue;
BigInteger ab = a.add(b);
|