Higher n higher

Kapil is climbing the steps of his office after meeting Anshuman. The length of a step must be nonnegative and can be by one bigger than, equal to, or one smaller than the length of the previous step. Since his time is very precious he needs to do this using the minimum number of steps in order to get from x to y. He needs your help for designing an algorithm for this feat. The length of the first and the last step must be one.

What is the minimum number of steps in order to get from x to y? The length of the first and the last step must be 1.

 

Input and Output 

Input consists of a line containing n, the number of test cases. For each test case, a line follows with two integers: 0 < x < y < 2^31. For each test case, print a line giving the minimum number of steps to get from x to y.

 

Sample Input 

3

17 41

1 41

14604 32391

 

Sample Output 

9

12

266
The solution is to create the following pattern based on the step count difference from start to destination (y-x+1):
Difference: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ….
Min. Steps: 2 3 3 4 4 5 5 5   6    6   6   7   7   7   7    8    8   8   8   9    9   9    9   9  10 10 10 10 10 11 ….

using System;

using System.Collections.Generic;

using System.Collections;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication2

{

    class Program

    {

        static void Main(string[] args)

        {

            int x = 14604;

            int y = 32391;

            int groupLength = 1, groupCount = 1;

            int elementCount = 0, minStepCount = 2;

            for (int i = 2; i <= (y – x + 1); i++)

            {

                elementCount++;

                if (elementCount > groupLength)

                {

                    if (groupCount == 0)

                    {

                        elementCount = 1;

                        minStepCount++;

                        groupCount++;

                    }

                    else

                    {

                        elementCount = 1;

                        minStepCount++;

                        groupCount = 0;

                        groupLength++;

                    }

                }

                //Console.WriteLine(i + " –> " + minStepCount);

            }

            Console.WriteLine("Minimum number of steps from " + x + " to " + y + " is " + minStepCount);

        }

    }

}

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s