Count the minimum steps to reach 0 from the given integer N
Last Updated :
20 Feb, 2023
Given two integers N and K where K represents the number of jumps that we are allowed to make directly from N reducing N to N – K, our task is to count minimum steps to reach 0 following the given operations:
- We can jump by a amount of K from N that is N = N – K
- Decrement N by 1 that is N = N -1.
Examples:
Input: N = 11, K = 4
Output: 5
Explanation:
For the given value N we can perform the operation in the given sequence: 11 -> 7 -> 3 -> 2 -> 1 -> 0
Input: N = 6, K = 3
Output: 2
Explanation:
For the given value N we can perform the operation in the given sequence: 6 -> 3 -> 0.
Approach:
To solve the problem mentioned above we know that it will take N / K steps to directly jump from value N to least divisible value with K and N % K steps to decrement it by 1 such as to reduce the count to 0. So the total number of steps required to reach 0 from N will be
(N / K) + (N % K)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getMinSteps( int n, int jump)
{
int quotient = n / jump;
int remainder = n % jump;
int steps = quotient + remainder;
return steps;
}
int main()
{
int N = 6, K = 3;
cout << getMinSteps(N, K);
return 0;
}
|
Java
class GFG{
static int getMinSteps( int n, int jump)
{
int quotient = n / jump;
int remainder = n % jump;
int steps = quotient + remainder;
return steps;
}
public static void main(String[] args)
{
int N = 6 , K = 3 ;
System.out.print(getMinSteps(N, K));
}
}
|
Python3
def getMinSteps(n, jump):
quotient = int (n / jump)
remainder = n % jump
steps = quotient + remainder
return steps
N = 6
K = 3
print (getMinSteps(N, K))
|
C#
using System;
class GFG{
static int getMinSteps( int n, int jump)
{
int quotient = n / jump;
int remainder = n % jump;
int steps = quotient + remainder;
return steps;
}
public static void Main( string [] args)
{
int N = 6, K = 3;
Console.Write(getMinSteps(N, K));
}
}
|
Javascript
<script>
function getMinSteps(n, jump)
{
let quotient = Math.floor(n / jump);
let remainder = n % jump;
let steps = quotient + remainder;
return steps;
}
let N = 6, K = 3;
document.write(getMinSteps(N, K));
</script>
|
Time Complexity: O(1).
We are using constant time to compute the minimum steps to reach 0 from N.
Space Complexity: O(1).
We are not using any extra space for computing the steps.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...