给定数字N,任务是通过在最小操作数X中加1或2来形成N(从0开始),以使X可被M整除。
例子:
Input: N = 10, M = 2
Output: X = 6
Explanation:
Taken operations are 2 2 2 2 1 1
X = 6 which is divisible by 2
Input: N = 17, M = 4
Output: 8
方法:
- 由于我们一次可以采取1步或2步,因此我们可以说最小否。采取的步骤数为n / 2,最大值为。步长为n,与否无关。的步数可被m整除。
- 因此,我们必须计算n / 2步才能获得最少的步数。现在,如果n为偶数,则最小步数将为n / 2,但是如果它为奇数,则它将为n / 2 + 1,而与否无关。的步数可被m整除。要使最小步长为m的倍数,我们可以执行floor((minimum_steps + m – 1)/ m)* m
- 同样,如果n小于m,则不可能找到最小步数,在这种情况下,我们将返回-1。
下面是上述方法的实现:
C++
// C++ program to find minimum
// number of steps to cover distance x
#include
using namespace std;
// Function to calculate the minimum number of steps required
// total steps taken is divisible
// by m and only 1 or 2 steps can be taken at // a time
int minsteps(int n, int m)
{
// If m > n ans is -1
if (m > n) {
return -1;
}
// else discussed above approach
else {
return ((n + 1) / 2 + m - 1) / m * m;
}
}
// Driver code
int main()
{
int n = 17, m = 4;
int ans = minsteps(n, m);
cout << ans << '\n';
return 0;
}
Java
// Java program to find minimum
// number of steps to cover distance x
class GFG
{
// Function to calculate the
// minimum number of steps required
// total steps taken is divisible
// by m and only 1 or 2 steps can be
// taken at // a time
static int minsteps(int n, int m)
{
// If m > n ans is -1
if (m > n)
{
return -1;
}
// else discussed above approach
else
{
return ((n + 1) / 2 + m - 1) / m * m;
}
}
// Driver code
public static void main (String[] args)
{
int n = 17, m = 4;
int ans = minsteps(n, m);
System.out.println(ans);
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 program to find minimum
# number of steps to cover distance x
# Function to calculate the minimum number of
# steps required total steps taken is divisible
# by m and only 1 or 2 steps can be taken at a time
def minsteps(n, m):
# If m > n ans is -1
if (m > n):
return -1
# else discussed above approach
else :
return ((n + 1) // 2 + m - 1) // m * m;
# Driver code
n = 17
m = 4
ans = minsteps(n, m)
print(ans)
# This code is contributed by Mohit Kumar
C#
// C# program to find minimum
// number of steps to cover distance x
using System;
class GFG
{
// Function to calculate the
// minimum number of steps required
// total steps taken is divisible
// by m and only 1 or 2 steps can be
// taken at // a time
static int minsteps(int n, int m)
{
// If m > n ans is -1
if (m > n)
{
return -1;
}
// else discussed above approach
else
{
return ((n + 1) / 2 + m - 1) / m * m;
}
}
// Driver code
public static void Main (String[] args)
{
int n = 17, m = 4;
int ans = minsteps(n, m);
Console.WriteLine(ans);
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
12
时间复杂度: O(1)