Basically, find x and y given the product = xy and sum = x + y. I would like review on optimization, clean code, and complexity. It looks like O(1), but the while
loop makes me wonder if it's something different.
/**
* x will always be less than or equal to y.
*/
final class Variables {
private final int x;
private final int y;
Variables(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override public String toString() {
return " x = " + x + " y = " + y;
}
}
/**
* @author SERVICE-NOW\ameya.patil
*/
public final class SimultaneousEquations {
private SimultaneousEquations () {}
/**
* Provided we dont have positive product and -ve sum,
* return value would be the smallest posive integer of the variable.
*
* @param product : product of x and y
* @param sum : sum of x and y
* @return : smallest positive integer of x and y.
*/
private static int getX(int product, int sum) {
assert product != 0;
assert product < 0 || (product > 0 && sum > 0);
int x = 1;
while (x*x != (sum * x - product)) {
x++;
}
return x;
}
/**
* Given a product and a sum, return two variables.
*
* @param sum : sum of two variables
* @param product : product of two variables
*/
public static Variables getVariables(int product, int sum) {
if (product == 0) {
if (sum < 0) {
return new Variables(sum, 0);
} else {
return new Variables(0, sum);
}
}
if (product < 0) {
int x = getX(product, sum);
return new Variables(product/x, x);
}
if (sum < 0) {
int x = -getX(product, -sum);
return new Variables(product/x, x);
}
int x = getX(product, sum);
return new Variables(x, product/x);
}
public static void main(String[] args) {
// 0 10
Variables v1 = SimultaneousEquations.getVariables(0, 10);
boolean result1 = v1.getX() == 0 && v1.getY() == 10;
System.out.println(result1);
// 2 5
Variables v2 = SimultaneousEquations.getVariables(10, 7);
boolean result2 = v2.getX() == 2 && v2.getY() == 5;
System.out.println(result2);
// -2 5
Variables v3 = SimultaneousEquations.getVariables(-10, 3);
boolean result3 = v3.getX() == -2 && v3.getY() == 5;
System.out.println(result3);
// 2 -5
Variables v4 = SimultaneousEquations.getVariables(-10, -3);
boolean result4 = v4.getX() == -5 && v4.getY() == 2;
System.out.println(result4);
// -2 -5
Variables v5 = SimultaneousEquations.getVariables(10, -7);
boolean result5 = v5.getX() == -5 && v5.getY() == -2;
System.out.println(result5);
}
}