Minimize operations to reduce A or B to 0 by reducing A from B or B from A
Last Updated :
22 Jun, 2022
Given two numbers A and B, the task is to find the minimum number of operations required to reduce either A or B to 0, wherein each operation A can be reduced by B if A is greater than equal to B, or vice versa.
Examples:
Input: A = 5, B = 4
Output: 5
Explanation:
Reduce B from A: A=1, B=4
Reduce A from B: A=1, B=3
Reduce A from B: A=1, B=2
Reduce A from B: A=1, B=1
Reduce B from A: A=0, B=1
Input: A=1, B=1
Output: 1
Explanation:
Reduce A from B: A=0, B=0
Approach: The approach to solving this problem is simply to check for bigger numbers and reduce the small number from it.
- Repeat following operations till at least one of the two numbers become 0
- If A is greater than equal to B, reduce B from A
- If A is smaller than A, reduce A from B
- For each loop iteration, store the count.
- Return the count of loop iterations at the end.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int countOperations( int num1, int num2)
{
int cnt = 0;
while (num1 > 0 && num2 > 0) {
if (num1 >= num2)
num1 -= num2;
else
num2 -= num1;
cnt++;
}
return cnt;
}
int main()
{
int A = 5, B = 4;
cout << countOperations(A, B);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int countOperations( int num1, int num2)
{
int cnt = 0 ;
while (num1 > 0 && num2 > 0 ) {
if (num1 >= num2)
num1 -= num2;
else
num2 -= num1;
cnt++;
}
return cnt;
}
public static void main (String[] args) {
int A = 5 , B = 4 ;
System.out.println(countOperations(A, B));
}
}
|
Python3
def countOperations(num1, num2):
cnt = 0
while (num1 > 0 and num2 > 0 ):
if (num1 > = num2):
num1 - = num2
else :
num2 - = num1
cnt + = 1
return cnt
A,B = 5 , 4
print (countOperations(A, B))
|
C#
using System;
class GFG {
static int countOperations( int num1, int num2)
{
int cnt = 0;
while (num1 > 0 && num2 > 0) {
if (num1 >= num2)
num1 -= num2;
else
num2 -= num1;
cnt++;
}
return cnt;
}
public static void Main()
{
int A = 5, B = 4;
Console.Write(countOperations(A, B));
}
}
|
Javascript
<script>
function countOperations(num1, num2) {
let cnt = 0;
while (num1 > 0 && num2 > 0) {
if (num1 >= num2)
num1 -= num2;
else
num2 -= num1;
cnt++;
}
return cnt;
}
let A = 5, B = 4;
document.write(countOperations(A, B));
</script>
|
Time Complexity: 0(MAX(A, B)), where A and B are the two numbers given.
Auxiliary Space: 0(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...