Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transformation of a number to different number using recursion

I am trying to make an algorithm for the following task:

  • I have two integers a ≤ b
  • The algorithm has to transform a into b by adding 1 and multiply by 2 operations. For example, if a = 5 and b = 23 the program should output something like 23 = ((5 * 2 + 1) * 2 + 1)
  • I have to use recursion

I've already Googled many times but all I could find is ideas on how to transform a matrix, how to do geometric transformations, how to transform string into another string and similar stuff.

Does anybody have any ideas?

like image 269
Nath Avatar asked May 27 '11 20:05

Nath


1 Answers

This is the way to find the transformation with the minimum number of operations:

(EDIT: Added parenthesis)

public static void main (String [] args)
{
    int a = 5, b = 23;
    System.out.println (transform (a, b) + " = " + b);
}

public static String transform (int a, int b)
{
    if (a == b) return "" + a;
    if (b % 2 == 0 && 2 * a <= b)
    {
        b = b / 2;
        return transform (a, b) + " * 2";
    }
    else
    {
        b = b - 1;
        return "(" + transform (a, b) + " + 1)";
    }
}
like image 54
Hyperboreus Avatar answered Oct 03 '22 02:10

Hyperboreus