Pythagorean triples: Difference between revisions

m
→‎{{header|Java}}: Added optimizations inspired by C, hey cool my IDE at home converted tabs to spaces for me
(→‎{{header|C}}: semi-optimized code)
m (→‎{{header|Java}}: Added optimizations inspired by C, hey cool my IDE at home converted tabs to spaces for me)
Line 63:
=={{header|Java}}==
[[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>import java.math.BigInteger;
import java.math.BigInteger;
import static java.math.BigInteger.ONE;
 
public class PythTrip{
public static void main(String[] args){
long tripCount = 0, primCount = 0;
 
public static void main(String[] args){
//change this to whatever perimeter limit you want;the RAM's the limit
long tripCount = 0, primCount = 0;
BigInteger periLimit = new BigInteger("100");
 
//change this to whatever perimeter limit you want;the RAM's the limit
for(BigInteger a = BigInteger.ONE;
BigInteger periLimit = new BigInteger("10010000");,
a.compareTo(periLimit) < 0; a = a.add(BigInteger.ONE)){
peri2 = periLimit.divide(new BigInteger("2")),
peri3 = periLimit.divide(new BigInteger("3"));
 
for(BigInteger ba = newONE; BigIntegera.compareTo(peri3) < 0; a = a.toStringadd(ONE));{
BigInteger aa = a.multiply(a);
b.compareTo(periLimit) < 0; b = b.add(BigInteger.ONE)){
for(BigInteger ab = new BigInteger(a.toString()).add(ONE);
a b.compareTo(periLimitperi2) < 0; ab = ab.add(BigInteger.ONE)){
BigInteger bb = b.multiply(b);
BigInteger ab = a.add(b);
BigInteger aabb = aa.add(bb);
for(BigInteger c = new BigInteger(b.toString()).add(ONE);
b c.compareTo(periLimitperi2) < 0; bc = bc.add(BigInteger.ONE)){
 
int compare = aabb.compareTo(c.multiply(c));
for(BigInteger c = new BigInteger(b.toString());
//if a+b+c > periLimit
c.compareTo(periLimit) < 0; c = c.add(BigInteger.ONE)){
if(ab.add(c).compareTo(periLimit) > 0){
break;
}
//if a^2 + b^2 != c^2
if(compare < 0){
break;
}else if (compare == 0){
tripCount++;
System.out.print(a + ", " + b + ", " + c);
 
//does binary GCD under the hood
//if a+b+c > periLimit
if(a.addgcd(b).add(c).compareTo(periLimitONE) >== 0)break;{
System.out.print(" primitive");
//if a^2 + b^2 != c^2
primCount++;
if(a.pow(2).add(b.pow(2)).compareTo(c.pow(2)) != 0)
}
continue;
System.out.println();
}
tripCount++;
}
System.out.print(a +", "+b+", "+c);
}
}
//does binary GCD under the hood
System.out.println("Up to a perimeter of " + periLimit + ", there are "+
if(a.gcd(b).compareTo(BigInteger.ONE) == 0){
+ tripCount + " triples, of which " + primCount + " are primitive.");
System.out.print(" primitive");
}
primCount++;
}
System.out.println();
}
}
}
System.out.println("Up to a perimeter of "+periLimit+", there are "+
tripCount+" triples, of which "+primCount+" are primitive.");
}
}</lang>
Output:
Anonymous user