Form N by adding 1 or 2 in minimum number of operations X where X is divisible by M
Last Updated :
01 Mar, 2022
Given a number N, the task is to form N (from 0) by adding 1 or 2 in the minimum number of operations X such that X is divisible by M.
Examples:
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: 12
Approach:
- As we can take either 1 or 2 steps at a time, so we can say that minimum no. of steps taken is n/2, and the maximum no. of steps is n, irrespective of that the no. of steps are divisible by m.
- So we have to count n/2 steps to get a minimum number of steps. Now if n is even, then a minimum number of steps will be n/2, but if it is odd, then it will be n/2+1, irrespective of that the no. of steps are divisible by m. To make minimum steps of a multiple of m we can do floor((minimum_steps + m – 1)/m) * m
- Also if n is less than m, then it is not possible to find the minimum number of steps, and in that case, we will return -1.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minsteps( int n, int m)
{
if (m > n) {
return -1;
}
else {
return ((n + 1) / 2 + m - 1) / m * m;
}
}
int main()
{
int n = 17, m = 4;
int ans = minsteps(n, m);
cout << ans << '\n' ;
return 0;
}
|
Java
class GFG
{
static int minsteps( int n, int m)
{
if (m > n)
{
return - 1 ;
}
else
{
return ((n + 1 ) / 2 + m - 1 ) / m * m;
}
}
public static void main (String[] args)
{
int n = 17 , m = 4 ;
int ans = minsteps(n, m);
System.out.println(ans);
}
}
|
Python3
def minsteps(n, m):
if (m > n):
return - 1
else :
return ((n + 1 ) / / 2 + m - 1 ) / / m * m;
n = 17
m = 4
ans = minsteps(n, m)
print (ans)
|
C#
using System;
class GFG
{
static int minsteps( int n, int m)
{
if (m > n)
{
return -1;
}
else
{
return ((n + 1) / 2 + m - 1) / m * m;
}
}
public static void Main (String[] args)
{
int n = 17, m = 4;
int ans = minsteps(n, m);
Console.WriteLine(ans);
}
}
|
Javascript
<script>
function minsteps(n , m)
{
if (m > n)
{
return -1;
}
else
{
return ((n + 1) / 2 + m - 1) / m * m;
}
}
var n = 17, m = 4;
var ans = minsteps(n, m);
document.write(ans);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...