Pythagorean triples: Difference between revisions
Content added Content deleted
(→{{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: | Line 63: | ||
=={{header|Java}}== |
=={{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. |
[[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> |
||
import java.math.BigInteger; |
|||
import static java.math.BigInteger.ONE; |
|||
public class PythTrip{ |
public class PythTrip{ |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
peri2 = periLimit.divide(new BigInteger("2")), |
|||
peri3 = periLimit.divide(new BigInteger("3")); |
|||
for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ |
|||
BigInteger aa = a.multiply(a); |
|||
⚫ | |||
⚫ | |||
⚫ | |||
BigInteger bb = b.multiply(b); |
|||
BigInteger ab = a.add(b); |
|||
BigInteger aabb = aa.add(bb); |
|||
⚫ | |||
⚫ | |||
int compare = aabb.compareTo(c.multiply(c)); |
|||
⚫ | |||
⚫ | |||
c.compareTo(periLimit) < 0; c = c.add(BigInteger.ONE)){ |
|||
if(ab.add(c).compareTo(periLimit) > 0){ |
|||
break; |
|||
} |
|||
⚫ | |||
if(compare < 0){ |
|||
break; |
|||
}else if (compare == 0){ |
|||
tripCount++; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
if(a.gcd(b).compareTo(ONE) == 0){ |
|||
⚫ | |||
⚫ | |||
primCount++; |
|||
if(a.pow(2).add(b.pow(2)).compareTo(c.pow(2)) != 0) |
|||
} |
|||
continue; |
|||
⚫ | |||
} |
|||
tripCount++; |
|||
} |
|||
⚫ | |||
} |
|||
} |
|||
⚫ | |||
⚫ | |||
if(a.gcd(b).compareTo(BigInteger.ONE) == 0){ |
|||
⚫ | |||
⚫ | |||
} |
|||
primCount++; |
|||
} |
|||
⚫ | |||
} |
|||
} |
|||
} |
|||
⚫ | |||
⚫ | |||
} |
|||
}</lang> |
}</lang> |
||
Output: |
Output: |