Pythagorean triples: Difference between revisions

Content added Content deleted
m (→‎{{header|Perl 6}}: minor rhetorical tweak)
(→‎{{header|Java}}: Added parent/child from Perl 6)
Line 333: Line 333:


=={{header|Java}}==
=={{header|Java}}==
===Brute force===
[[Category:Arbitrary precision]]Theoretically, this can go "forever", but it takes a while, so only the minimum is shown. Luckily, <code>BigInteger</code> has a GCD method built in.
[[Category:Arbitrary precision]]Theoretically, this can go "forever", but it takes a while, so only the minimum is shown. Luckily, <code>BigInteger</code> has a GCD method built in.
<lang java>
<lang java>
Line 405: Line 406:
24, 32, 40
24, 32, 40
Up to a perimeter of 100, there are 17 triples, of which 7 are primitive.</pre>
Up to a perimeter of 100, there are 17 triples, of which 7 are primitive.</pre>
===Parent/child===
{{trans|Perl 6}} (with limited modification for saving a few BigInteger operations)
{{works with|Java|1.5+}}
This can also go "forever" theoretically. Letting it go to another order of magnitude overflowed the stack on the computer this was tested on. This version also does not show the triples as it goes, it only counts them.
<lang java5>import java.math.BigInteger;

public class Triples{
public static BigInteger LIMIT;
public static final BigInteger TWO = BigInteger.valueOf(2);
public static final BigInteger THREE = BigInteger.valueOf(3);
public static final BigInteger FOUR = BigInteger.valueOf(4);
public static final BigInteger FIVE = BigInteger.valueOf(5);
public static long primCount = 0;
public static long tripCount = 0;

//I don't know Japanese :p
public static void parChild(BigInteger a, BigInteger b, BigInteger c){
BigInteger perim = a.add(b).add(c);
if(perim.compareTo(LIMIT) > 0) return;
primCount++; tripCount += LIMIT.divide(perim).longValue();
BigInteger a2 = TWO.multiply(a), b2 = TWO.multiply(b), c2 = TWO.multiply(c),
c3 = THREE.multiply(c);
parChild(a.subtract(b2).add(c2),
a2.subtract(b).add(c2),
a2.subtract(b2).add(c3));
parChild(a.add(b2).add(c2),
a2.add(b).add(c2),
a2.add(b2).add(c3));
parChild(a.negate().add(b2).add(c2),
TWO.negate().multiply(a).add(b).add(c2),
TWO.negate().multiply(a).add(b2).add(c3));
}

public static void main(String[] args){
for(long i = 100; i <= 10000000; i*=10){
LIMIT = BigInteger.valueOf(i);
primCount = tripCount = 0;
parChild(THREE, FOUR, FIVE);
System.out.println(LIMIT + ": " + tripCount + " triples, " + primCount + " primitive.");
}
}
}</lang>
Output:
<pre>100: 17 triples, 7 primitive.
1000: 325 triples, 70 primitive.
10000: 4858 triples, 703 primitive.
100000: 64741 triples, 7026 primitive.
1000000: 808950 triples, 70229 primitive.
10000000: 9706567 triples, 702309 primitive.</pre>


=={{header|Perl 6}}==
=={{header|Perl 6}}==