Search code examples
javamath

I want to find a number with some conditions


I have this problem in mind, and I think there is a solution, but im not finding one

a*x = z
b*y = t
a+b < z && a+b < t && z<=t

This is my code

public static double solveEquation(double a, double x, double y) {
    double z = a * x; // Calculate z
    System.out.println("z: " + z);
    double b = z / y - a; // Calculate b
    System.out.println("b: " + b);
    double t = b * y;  // Calculate t
    System.out.println("t: " + t);
    
    

    if (a + b < z && a + b < t && z <= t) {
        return b;
    }
    return Double.NaN; // Return NaN if no solution found
}

the best case was if I only give the 'x' and 'y' and then it will find me the 'a' and the 'b'

I tried the method above but I cant get the right result


Solution

  • For now, assuming the values a, x and y to be positive (and non-zero): -

    Since z <= t, we technically only have to satisfy two conditions:

    1. z <= t Which translates to a * x <= b * y
    2. a + b < z

    Due to positive numbers constraints, we can simplify the first one to:

    b >= (a * x) / y

    So, I think this code should do what you want:

    public static double solveEquation(double a, double x, double y) {
        double z = a * x; // Calculate z
        System.out.println("z: " + z);
        double b = z / y; // Calculate b
        System.out.println("b: " + b);
        double t = b * y;  // Calculate t
        System.out.println("t: " + t);
        
        
    
        if (a + b < z && z <= t) {
            return b;
        }
        return Double.NaN; // Return NaN if no solution found
    }