Anonymous user
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 static java.math.BigInteger.ONE;
public class PythTrip{
public static void main(String[] args){▼
long tripCount = 0, primCount = 0;▼
//change this to whatever perimeter limit you want;the RAM's the limit▼
BigInteger periLimit = new BigInteger("100");▼
for(BigInteger a = BigInteger.ONE;▼
a.compareTo(periLimit) < 0; a = a.add(BigInteger.ONE)){▼
peri2 = periLimit.divide(new BigInteger("2")),
peri3 = periLimit.divide(new BigInteger("3"));
BigInteger aa = a.multiply(a);
b.compareTo(periLimit) < 0; b = b.add(BigInteger.ONE)){▼
BigInteger bb = b.multiply(b);
BigInteger ab = a.add(b);
BigInteger aabb = aa.add(bb);
int compare = aabb.compareTo(c.multiply(c));
▲ for(BigInteger c = new BigInteger(b.toString());
if(ab.add(c).compareTo(periLimit) > 0){
break;
}
if(compare < 0){
break;
}else if (compare == 0){
tripCount++;
▲ //if a+b+c > periLimit
▲ //if a^2 + b^2 != c^2
primCount++;
}
}
}
▲ System.out.print(a +", "+b+", "+c);
}
}
▲ //does binary GCD under the hood
▲ System.out.print(" primitive");
}
▲ System.out.println();
▲ System.out.println("Up to a perimeter of "+periLimit+", there are "+
▲ tripCount+" triples, of which "+primCount+" are primitive.");
}</lang>
Output:
|