所以我尝试使用java制作一个程序。它的输入是整数,整数被认为是3个整数a、b和c(· a^2 + b^2 = c^2
)之和,它的输出是c^2。为此,我扩展了等式并合并a^2 + b^2 - c^2 = 0
,c = sum - a - b
得到Math.pow(sum, 2) - 2 * sum * (a + b) + 2 * a * b
。然后我得到a + b <= sum*2/3
然后我将a,b的所有组合代入等式中以查看它何时为零。
这是我的代码:
/** Pythagorean Triples
* test case for small numbers
* Tony
*/
import java.util.*;
public class Solution54 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
for (int i = 0; i < times; i++) {
/* prompt the sum and get the equation:
* Math.pow(sum, 2) - 24 * (a + b) + 2a*b = 0;
* we consider b >= a;
*/
double sum = sc.nextDouble();
double ablimits = Math.floor(sum / 3 * 2); // a + b <= ablimits
double alimits = Math.floor(ablimits / 2); // a <= alimits
//System.out.println("another round");
//System.out.print(alimits + " " + blimits);
A: for (double a = 1; a <= alimits; a++) {
B: for (double b = a; b <= sum - a; b++) {
double result = Math.pow((sum-a-b),2)-a*a-b*b;
//System.out.print("when a is " + a + " " + "when b is " + b + ":" + result + ";");
if (Math.pow(sum, 2) - 2 * sum * (a + b) + 2 * a * b == 0) {
double answer = a*a + b*b;
int output = (int)answer;
System.out.print(output + " ");
break A;
}
}
}
}
}
}
当我输入1 12
时,它给出 25(因为a,b,c=3,4,5; c^2 = 25
),但它无法处理大输入,14808286
因为我的算法效率不够高。这样做的有效方法是什么?请!