给定两个整数n和m以及a和b ,在一次运算中, n可以乘以a或b 。任务是用最少的给定操作数将n转换为m 。如果无法通过给定的操作将n转换为m,则打印-1。
例子:
Input: n = 120, m = 51840, a = 2, b = 3
Output: 7
120 * 2 * 2 * 2 * 2 * 3 * 3 * 3 = 51840
Input: n = 10, m = 50, a = 5, b = 7
Output: 1
10 * 5 = 50
在上一篇文章中,我们讨论了使用除法的方法。
在本文中,我们将使用一种方法来使用递归查找最少数量的操作。递归将包含两个状态,数字乘以a或b并计算步数。这两个步骤中最少的一个就是答案。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
#define MAXN 10000000
// Function to find the minimum number of steps
int minimumSteps(int n, int m, int a, int b)
{
// If n exceeds M
if (n > m)
return MAXN;
// If N reaches the target
if (n == m)
return 0;
// The minimum of both the states
// will be the answer
return min(1 + minimumSteps(n * a, m, a, b),
1 + minimumSteps(n * b, m, a, b));
}
// Driver code
int main()
{
int n = 120, m = 51840;
int a = 2, b = 3;
cout << minimumSteps(n, m, a, b);
return 0;
}
Java
// Java implementation of the above approach
class GFG
{
static int MAXN = 10000000;
// Function to find the minimum number of steps
static int minimumSteps(int n, int m, int a, int b)
{
// If n exceeds M
if (n > m)
return MAXN;
// If N reaches the target
if (n == m)
return 0;
// The minimum of both the states
// will be the answer
return Math.min(1 + minimumSteps(n * a, m, a, b),
1 + minimumSteps(n * b, m, a, b));
}
// Driver code
public static void main (String[] args)
{
int n = 120, m = 51840;
int a = 2, b = 3;
System.out.println(minimumSteps(n, m, a, b));
}
}
// This code is contributed by ihritik
Python3
# Python 3 implementation of the
# above approach
MAXN = 10000000
# Function to find the minimum
# number of steps
def minimumSteps(n, m, a, b):
# If n exceeds M
if (n > m):
return MAXN
# If N reaches the target
if (n == m):
return 0
# The minimum of both the states
# will be the answer
return min(1 + minimumSteps(n * a, m, a, b),
1 + minimumSteps(n * b, m, a, b))
# Driver code
if __name__ == '__main__':
n = 120
m = 51840
a = 2
b = 3
print(minimumSteps(n, m, a, b))
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the above approach
using System;
class GFG
{
static int MAXN = 10000000;
// Function to find the minimum number of steps
static int minimumSteps(int n, int m, int a, int b)
{
// If n exceeds M
if (n > m)
return MAXN;
// If N reaches the target
if (n == m)
return 0;
// The minimum of both the states
// will be the answer
return Math.Min(1 + minimumSteps(n * a, m, a, b),
1 + minimumSteps(n * b, m, a, b));
}
// Driver code
public static void Main ()
{
int n = 120, m = 51840;
int a = 2, b = 3;
Console.WriteLine(minimumSteps(n, m, a, b));
}
}
// This code is contributed by ihritik
PHP
$m)
return $MAXN;
// If N reaches the target
if ($n == $m)
return 0;
// The minimum of both the states
// will be the answer
return min(1 + minimumSteps($n * $a, $m, $a, $b),
1 + minimumSteps($n * $b, $m, $a, $b));
}
// Driver code
$n = 120; $m = 51840;
$a = 2; $b = 3;
echo minimumSteps($n, $m, $a, $b);
// This code is contributed by Akanksha Rai
?>
输出:
7