Problem 39
Integer right triangles
If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.
For which value of p ≤ 1000, is the number of solutions maximised?
整数边长直角三角形
若三边长{a,b,c}均为整数的直角三角形周长为p,当p = 120时,恰好存在三个不同的解:
在所有的p ≤ 1000中,p取何值时有解的数目最多?
@Test
public void test(){
System.out.println(getLargest(1000));
}
public int getLargest(int limit){
Map<Integer, Integer> perimeterMap = new HashMap<Integer, Integer>();
for( int i = 12; i <= limit ; i ++){
for( int a = i - 1; a > 1; a -- ){
for( int b = a - 1; b > 0; b --){
int c = i - a - b;
if( c < 0){
continue;
}
if( a * a + b * b == c * c ){
int perimeter = i;
if( !perimeterMap.containsKey(perimeter)){
perimeterMap.put(perimeter, 0);
}
perimeterMap.put(perimeter, perimeterMap.get(perimeter) + 1);
}
}
}
}
int maxId = 0;
int maxVal = 0;
for( Entry<Integer, Integer> entry : perimeterMap.entrySet()){
int key = entry.getKey();
int val = entry.getValue();
if( key <= limit && val > maxVal){
maxId = key;
maxVal = val;
}
}
System.out.println("maxId=" + maxId + ",maxVal=" + maxVal);
return maxVal;
}
/**
* x = 2 * a * b;
* y = a * a - b * b;
* z = a * a + b * b;
* 2 | x; a > b > 0;
*
* (a % 2 == 0 && b % != 0 ) || ( a % 2 != 0 && b % 2 == 0)
*
* x + y + z = 2 * a ( a + b ) = 1000
* @return
*/
public int getLargestId(int limit){
int a = (int)(limit / 2);
Map<Integer, Integer> perimeterMap = new HashMap<Integer, Integer>();
for( ; a > 0 ; a --){
for( int b = a - 1; b > 0 ; b = b - 1){
int perimeter = 2 * a * ( a + b);
System.out.println(perimeter);
if( !perimeterMap.containsKey(perimeter)){
perimeterMap.put(perimeter, 0);
}
perimeterMap.put(perimeter, perimeterMap.get(perimeter) + 1);
}
}
int maxId = 0;
int maxVal = 0;
for( Entry<Integer, Integer> entry : perimeterMap.entrySet()){
int key = entry.getKey();
int val = entry.getValue();
if( key <= limit && val > maxVal){
maxId = key;
maxVal = val;
}
}
System.out.println("maxId=" + maxId + ",maxVal=" + maxVal);
return maxVal;
}