Search code examples
algorithmmathlanguage-agnostic

what is the most efficient way to search the result of x+y=x*y if I know x?


for example:

6+1.2=6*1.2
5+1.25=5*1.25

I want to try to write a program to search the result like search prime number:

public class Test{
    public static void main(String[] args){
        float x=-1.0f;
        float d=0.0001f;
        for(float y=-10;y<10;y=y+d){
            if(x+y-x*y>=-d && x+y-x*y<=d){
                System.out.println(y);
            }
        }
    }
}

but the program has some problem:

  1. It can search result from -10 to 10 only, because search between Float.MIN_VALUE and Float.MAX_VALUE is too slow
  2. I know 9+1.125=9*1.125, but even I set each increment is 0.0001, the program cannot find any result
  3. sometimes the program print multiple result around the real result

Is there any other faster method or better algorithm to find the result?


Solution

  • Algebraically:

    y = x / (x - 1)
    

    It will be significantly faster than trying to iterate your way towards an answer.

    As mentioned below, don't forget to catch x = 0