求一个正整数加上正整数x是一个完全平方数,加上正整数y还是一个完全平方数。输入两个正整数x,y。打印所有解。
public class Demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
scanner.close();
//把输入的数字大数字放在x,小数字放在y
if (x < y) {
x = x ^ y;
y = x ^ y;
x = y ^ x;
}
if (x == y || y <= 0) {
//满足这些条件不计算
System.out.println(MESSAGE);
} else {
calculation(x, y);
}
}
public static void calculation(int x, int y) {
double t = getLoopNumber(x, y); //计算出循环次数
int k = 0; //用来判断是否有解,k>0有解
while (t > 0) {
double temp = (x - y) / t;
if (temp % 1 != 0) {
t--;
continue;
}
double a = (temp + t) / 2;
if (a % 1 != 0) {
t--;
continue;
}
double b = a - t;
int r = (int) (b * b - y);
System.out.println("满足条件的数字:" + r);
System.out.println(r + "+" + y + "=" + (r + y) + "开方得 " + (int) Math.sqrt(r + y) + "\t" + r + "+" + x + "="
+ (r + x) + "开方得 " + (int) Math.sqrt(r + x));
t--;
k++;
}
if (k == 0) {
System.out.println("不存在这样的正整数");
}
}
public static double getLoopNumber(int x, int y) {
double a = Math.ceil(Math.sqrt(x));
double b = Math.ceil(Math.sqrt(y));
double t = (x - y) / (a + b);
return Math.floor(t);
}
private static final String MESSAGE = "你特么在逗我!";
}