A
A
Andrew2020-01-26 03:36:16
Mathematics
Andrew, 2020-01-26 03:36:16

How to find the minimum number of operations?

I am not strong in mathematics, the following task is
given: x, y are given.
How to get the number y from the number x, using only the operations (x * 2) and (x - 1), while spending the least number of attempts?
You can implement simple logic in the forehead, if x is less then we multiply, if more, then we subtract. But there are cases where this will not work, for example x = 5, y = 8.
Here the minimum of operations is 2: x - 1, x * 2, while a primitive algorithm would make three attempts: x * 2, x -1, x - one.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey〒., 2020-01-26
@AndrewRusinas

Algorithm :

int convert(x, y) {
    if (x == y)  {
        return 0;
    }
    
    // невозможно преобразовать
    if (x <= 0 && y > 0) {
        return -1;
    }

    // x больше y
    if (x > y) 
        return x - y;

    if (y % 2 == 1) {   // y нечётное число
       return 1 + convert(x, y + 1); // выполняем 'x - 1' 
    } else {    // y чётное
        return 1 + convert(m, n/2); // выполняем 'x * 2'
    }
}

Source

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question