Open In App

Minimum moves to make X = Y by adding or subtracting numbers starting from 1

Given 2 integers X and Y, make X = Y by performing the following operation:

Start 'i' from 1 and continue till N(minimum number of moves). Then there are 2 cases:

  1. If 'i' is odd, subtract i from either X or Y
  2. If 'i' is even, add i to either X or Y

Find the minimum number of moves required (minimum value of N) for which these 2 elements can be made equal, else return -1, if it is not possible.

Examples:

Input: X = 5, Y = 14
Output: 5
Explanation:

  • When i = 1, subtract i from Y = 14, so new value of Y = 13
  • Next, i = 2, add i to X = 5, so new value of X = 7
  • When i = 3, subtract i from X = 7, so new value of X = 4
  • When i = 4, add i to X, so new value of X = 8
  • When i = 5, subtract i from Y = 13, so new value of Y = 8

Thus, X = Y = 8, after 5 operations which is the minimum number of operations to be done.

Input: X = 7, Y = 13
Output: 3
Explanation:

  • When i = 1, subtract i from Y = 13, so new value of Y = 12
  • Next, i = 2, add i to X = 7, so new value of X =9
  • When i = 3, subtract i from Y = 12, so new value of Y = 9

Thus, X = Y = 9, after 3 operations which is the minimum number of operations to be done.

Approach: To solve the problem, follow the below idea:

We can say that the number of steps needed does not depend on whether 'i' is even or odd because let's say, when 'i' is odd, subtracting from either X or Y would mean adding 'i' to either Y or X respectively, as what matters is reducing the absolute difference between X and Y.

Let the absolute difference between X and Y be 'd'. Now, we keep on reducing the difference by either adding or subtracting 'i' to the required number each step, which would be minimum when at each step, 'i' contributes to reducing the difference upto a threshold, after which it might exceed 'd'. Thus,

dt = threshold, and the last step be at 'i' = n. So, to determine n:

1 + 2 + .. + n = d
n * (n+1)/2 = d
n2 + n - 2d = 0
n = (-1 + sqrt(1 + 8d))/2

Now, current sum = 1 + 2 + .. + n = n*(n+1)/2

If current sum = d, then minimum number of steps required = n, else

To make 'current sum' = d, in minimum number of steps, we need to keep on adding (n + 1), (n + 2), .. to 'current sum', until the difference between 'current sum' and d becomes even. Let's say at any step m (m > n), the current sum = m*(m + 1)/2 and

h = abs(current sum - d)

where h is a even number.

Then we can reverse the number value at 'h/2' step from +'h/2' to -'h/2', so that our current sum decreases by a value equal to 'h'.

Step-by-step algorithm:

Below is the implementation of the above problem.

#include <bits/stdc++.h>
using namespace std;

int main()
{
      // Sample Input
    int X = 15, Y = 100;
      // Store the absolute difference in d
    int d = abs(X - Y);
  
      // If X = Y, then return 0
    if (d == 0) {
        cout << 0 << endl;
    }
    else {
          // Find the minimum number of steps such that the absolute difference remains greater than or equal to 0
        int n = (-1 + sqrt(1 + 8 * d)) / 2;
          // Find the sum subtracted after n steps
        int current_sum = n * (n + 1) / 2;
          // If after n steps, the current_sum becomes equal to d, then return n as the total number of steps
        if (current_sum == d)
            cout << "Minimum number of steps = " << n
                 << endl;
        else {
            n++;
            // incrementing the value of n in each step
            current_sum += n;
              // For the remaining difference, we keep on increasing h till h becomes an even number
            int h = current_sum - d;
            if (h % 2 == 0)
                cout << "Minimum number of steps = " << n
                     << endl;
            else {
                while (h % 2 != 0) {
                    n++;
                    current_sum += n;
                    h = current_sum - d;
                }
                cout << "Minimum number of steps = " << n
                     << endl;
            }
        }
    }
    return 0;
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Sample Input
        int X = 15, Y = 100;

        // Store the absolute difference in d
        int d = Math.abs(X - Y);

        // If X = Y, then return 0
        if (d == 0) {
            System.out.println(0);
        } else {
            // Find the minimum number of steps such that the absolute difference remains greater than or equal to 0
            int n = (int) ((-1 + Math.sqrt(1 + 8 * d)) / 2);
            // Find the sum subtracted after n steps
            int currentSum = n * (n + 1) / 2;
            // If after n steps, the currentSum becomes equal to d, then return n as the total number of steps
            if (currentSum == d) {
                System.out.println("Minimum number of steps = " + n);
            } else {
                n++;
                // incrementing the value of n in each step
                currentSum += n;
                // For the remaining difference, we keep on increasing h till h becomes an even number
                int h = currentSum - d;
                if (h % 2 == 0) {
                    System.out.println("Minimum number of steps = " + n);
                } else {
                    while (h % 2 != 0) {
                        n++;
                        currentSum += n;
                        h = currentSum - d;
                    }
                    System.out.println("Minimum number of steps = " + n);
                }
            }
        }
    }
}

// This code is contributed by shivamgupta310570
import math

# Sample Input
X = 15
Y = 100

# Store the absolute difference in d
d = abs(X - Y)

# If X = Y, then return 0
if d == 0:
    print(0)
else:
    # Find the minimum number of steps such that the absolute difference remains greater than or equal to 0
    n = int((-1 + math.sqrt(1 + 8 * d)) / 2)
    
    # Find the sum subtracted after n steps
    current_sum = n * (n + 1) / 2
    
    # If after n steps, the current_sum becomes equal to d, then return n as the total number of steps
    if current_sum == d:
        print("Minimum number of steps = ", n)
    else:
        n += 1
        # incrementing the value of n in each step
        current_sum += n
        
        # For the remaining difference, we keep on increasing h till h becomes an even number
        h = current_sum - d
        if h % 2 == 0:
            print("Minimum number of steps = ", n)
        else:
            while h % 2 != 0:
                n += 1
                current_sum += n
                h = current_sum - d
            print("Minimum number of steps = ", n)
// Sample Input
const X = 15;
const Y = 100;

// Store the absolute difference in d
const d = Math.abs(X - Y);

// If X = Y, then return 0
if (d === 0) {
    console.log(0);
} else {
    // Find the minimum number of steps such that the absolute difference remains greater than or equal to 0
    let n = Math.floor((-1 + Math.sqrt(1 + 8 * d)) / 2);

    // Find the sum subtracted after n steps
    let current_sum = (n * (n + 1)) / 2;

    // If after n steps, the current_sum becomes equal to d, then return n as the total number of steps
    if (current_sum === d) {
        console.log("Minimum number of steps =", n);
    } else {
        n += 1;
        // incrementing the value of n in each step
        current_sum += n;

        // For the remaining difference, we keep on increasing h till h becomes an even number
        let h = current_sum - d;
        if (h % 2 === 0) {
            console.log("Minimum number of steps =", n);
        } else {
            while (h % 2 !== 0) {
                n += 1;
                current_sum += n;
                h = current_sum - d;
            }
            console.log("Minimum number of steps =", n);
        }
    }
}

Output
Minimum number of steps = 13

Time Complexity: O(log(d)), where d = |a-b|
Auxiliary Space: O(1)

Article Tags :