通过从 B 中减少 A 或从 A 中减少 B 来最小化将 A 或 B 减少到 0 的操作
给定两个数字A和B ,任务是找到将 A 或 B 减少到 0 所需的最小操作数,其中如果A大于等于B,则每个操作A可以减少B ,反之亦然。
例子:
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
方法:解决这个问题的方法是简单地检查较大的数字并从中减少小数字。
- 重复以下操作,直到两个数字中的至少一个变为 0
- 如果 A 大于等于 B,则从 A 减少 B
- 如果 A 小于 A,则从 B 减少 A
- 对于每个循环迭代,存储计数。
- 最后返回循环迭代的计数。
下面是上述方法的实现:
C++
// C++ program to find Minimum number
// Of operations required to reduce
// Either A or B to Zero
#include
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;
}
// Driver Code
int main()
{
int A = 5, B = 4;
cout << countOperations(A, B);
return 0;
}
Java
// Java program to find Minimum number
import java.io.*;
class GFG {
// Of operations required to reduce
// Either A or B to Zero
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;
}
// Driver Code
public static void main (String[] args) {
int A = 5, B = 4;
System.out.println(countOperations(A, B));
}
}
// This code is contributed by hrithikgarg03188.
Python3
# Python code for the above approach
def countOperations(num1, num2):
cnt = 0
while (num1 > 0 and num2 > 0):
if (num1 >= num2):
num1 -= num2
else:
num2 -= num1
cnt += 1
return cnt
# Driver Code
A,B = 5,4
print(countOperations(A, B))
# This code is contributed by shinjanpatra
C#
// C# program to find Minimum number
// Of operations required to reduce
// Either A or B to Zero
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;
}
// Driver Code
public static void Main()
{
int A = 5, B = 4;
Console.Write(countOperations(A, B));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
5
时间复杂度: 0(N)
辅助空间: 0(1)