Wednesday, 27 Oct 2021

# Minimize divisions by 2, 3, or 5 required to make two given integers equal

Minimize divisions by 2, 3, or 5 required to make two given integers equal
Given two integers X and Y, the task is to make X and Y equal by dividing either of X or Y by 2, 3, or 5, minimum number of times, if found to be divisible. If the two integers can be made equal, then print “-1”.
Examples:

Input: X = 15, Y = 20Output: 3Explanation:Operation 1: Reduce X(= 15) to 15/3 i.e., X = 15/3 = 5.Operation 2: Reduce Y(= 20) to 20/2 i.e., Y = 20/2 = 10.Operation 3: Reduce Y(= 20) to 10/2 i.e., Y = 10/2 = 5.After the above operations, X and Y are equal i.e., 5.Therefore, the count of operation required is 3.
Input: X = 6, Y = 6Output: 0

Approach: The given problem can be solved greedily. The idea is to reduce the given integers to their GCD in order to make them equal. Follow the steps below to solve the problem:Find the Greatest Common Divisor (GCD) of X and Y and divide X and Y by their GCD.
Initialize a variable, say count, to store the number of divisions required.
Iterate until X is not equal to Y and perform the following steps:
If the value of X is greater than Y, then swap X and Y.
If the larger number(i.e., Y) is divisible by 2, 3, or 5, then divide it by that number. Increment count by 1. Otherwise, if it is not possible to make both the numbers equal, print “-1” and break out of the loop.

After completing the above steps, if both the numbers can be made equal, then print the value of count as the minimum number of divisions required to make X and Y equal.
Below is the implementation of the above approach:

C++

#include
using namespace std;

int gcd(int a, int b)
{

if (b == 0) {
return a;
}

return gcd(b, a % b);
}

void minimumOperations(int X, int Y)
{

int GCD = gcd(X, Y);

X = X / GCD;
Y = Y / GCD;

int count = 0;

while (X != Y) {

if (Y > X) {
swap(X, Y);
}

if (X % 2 == 0) {
X = X / 2;
}

else if (X % 3 == 0) {
X = X / 3;
}

else if (X % 5 == 0) {
X = X / 5;
}

else {
cout X) {
int t = X;
X = Y;
Y = t;
}

if (X % 2 == 0) {
X = X / 2;
}

else if (X % 3 == 0) {
X = X / 3;
}

else if (X % 5 == 0) {
X = X / 5;
}

else {
Console.WriteLine(“-1”);
return;
}

count++;
}

Console.WriteLine(count);
}

static public void Main()
{
int X = 15, Y = 20;
minimumOperations(X, Y);
}
}

Output:
3

Time Complexity: O(log(max(X, Y)))Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.