### Singular integer right triangles题号：75 难度： 25 中英对照

It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples.

12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)

In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles.

120 cm: (30,40,50), (20,48,52), (24,45,51)

Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed?

### Code

import java.util.*;

public final class p75 {
public static void main(String[] args) {
long start=System.nanoTime();
String result = run();
long end=System.nanoTime();
System.out.println(result);
System.out.println( (end-start)/1000000 + "ms" );
}
static public String run(){
final int LIMIT=1500000;
/*
* Pythagorean triples theorem:
*   Every primitive Pythagorean triple with a odd and b even can be expressed as
*   a = st, b = (s^2-t^2)/2, c = (s^2+t^2)/2, where s > t > 0 are coprime odd integers.
*/
Set<IntTriple> triples = new HashSet<>();
for (int s = 3; s * s <= LIMIT; s += 2) {
for (int t = s - 2; t > 0; t -= 2) {
if (gcd(s, t) == 1) {
int a = s * t;
int b = (s * s - t * t) / 2;
int c = (s * s + t * t) / 2;
if (a + b + c <= LIMIT)
}
}
}

byte[] ways = new byte[LIMIT + 1];
for (IntTriple triple : triples) {
int sum = triple.a + triple.b + triple.c;
for (int i = sum; i < ways.length; i += sum)
ways[i] = (byte)Math.min(ways[i] + 1, 2);  // Increment but saturate at 2
}

int count = 0;
for (int x : ways) {
if (x == 1)
count++;
}
return Integer.toString(count);
}

// Returns the largest non-negative integer that divides both x and y.
public static int gcd(int x, int y) {
if (x < 0 || y < 0)
throw new IllegalArgumentException("Negative number");
while (y != 0) {
int z = x % y;
x = y;
y = z;
}
return x;
}

private static final class IntTriple {

public final int a;
public final int b;
public final int c;

public IntTriple(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}

public boolean equals(Object obj) {
if (!(obj instanceof IntTriple))
return false;
else {
IntTriple other = (IntTriple)obj;
return a == other.a && b == other.b && c == other.c;
}
}

public int hashCode() {
return a + b + c;
}

}

}
161667
91ms