问题描述如下:
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.
{20,48,52}, {24,45,51}, {30,40,50}
For which value of p ≤ 1000, is the number of solutions maximised?
//方法一:自己的方法,时间是十秒左右,代码易懂,效率较低
public class Problem39
{
public static void main(String[] args)
{
int max = 0;
int num = 0;
long start = System.currentTimeMillis();
for (int i = 120; i <= 1000; i++)
{
if (isPerimeter(i) > max)
{
num = i;
max = isPerimeter(i);
}
}
long end = System.currentTimeMillis();
System.out.println("time:" + (end - start));
System.err.println(num + "\t" + max);
}
public static int isPerimeter(int num)
{
int maxNum = 0;
for (int a = 1; a < num / 2; a++)
{
for (int b = 1; b <= a; b++)
{
int c = num - a - b;
if (Math.pow(c, 2) == Math.pow(a, 2) + Math.pow(b, 2))
{
maxNum++;
}
}
}
return maxNum;
}
}
//方法二:效率特别高,83125ns,近乎0ms,缺点没看太明白
public class Problemr39_1
{
private static int[] perimeter = new int[1000];
public static void main(String args[])
{
int a, b, c;
int total;
long start = System.nanoTime();
for (int m = 2; m < 22; m++)
for (int n = m % 2 + 1; n < m; n += 2)
if (gcd(m, n) == 1)
{
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
total = a + b + c;
for (int loop = total; loop < 1000; loop += total)
perimeter[loop]++;
}
int max = -1;
int maxIndex = -1;
for (int loop = 0; loop < 1000; loop++)
if (perimeter[loop] > max)
{
max = perimeter[loop];
maxIndex = loop;
}
long end = System.nanoTime();
System.out.println("time:" + (end - start));
System.out.println("Maximum perimeter: " + maxIndex);
}
private static int gcd(int a, int b)
{
if (a == 1 || b == 1)
return 1;
else if (a % b == 0)
return b;
else if (b % a == 0)
return a;
else if (a > b)
return gcd(a - (a / b) * b, b);
else
return gcd(a, b - (b / a) * a);
}
}
//方法三:高效率,用时16ms
public class Problemr39_2
{
static int[] perimeters = new int[1001];
public static void main(String args[])
{
long start = System.currentTimeMillis();
findTriples();
System.out.println(findMax());
long end = System.currentTimeMillis();
System.out.println("time:" + (end - start));
}
public static int findMax()
{
int ans = 0;
int maxSol = 0;
for (int i = 0; i < perimeters.length; i++)
{
if (perimeters[i] > maxSol)
{
ans = i;
maxSol = perimeters[i];
}
}
return ans;
}
public static double hypotenuse(double a, double b)
{
return Math.sqrt((Math.pow(a, 2) + Math.pow(b, 2)));
}
public static void findTriples()
{
double a;
double b;
double c;
double p;
for (a = 1; a <= 1000; a++)
{
for (b = a + 1; a + b + hypotenuse(a, b) <= 1000; b++)
{
c = hypotenuse(a, b);
p = a + b + c;
if (p == (int) p && p <= 1000)
{
// System.out.println((int)a+"\t"+(int)b+"\t"+(int)c+"\t"+(int)p);
perimeters[(int) p]++;
}
}
}
}
}
result:
num = 840