Given two positive integers A and B where A is greater than B. In one move one can decrease A by 1 which implies that after one move A is equal to A – 1. The task is to find the minimum number of moves required to make A divisible by B in constant time.
Examples:
Input: A = 10, B = 3
Output: 1
Explanation: Only one move is required A = A – 1 = 9, which is divisible by 3.
Input : A = 10, B = 10
Output : 0
Explanation: Since A is equal to B therefore zero move required.
Approach:
To solve the problem mentioned above we take the modulus of the numbers that are A % B and the result is stored in a variable that is the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void movesRequired( int a, int b)
{
int total_moves = a % b;
cout << total_moves << "\n" ;
}
int main()
{
int A = 10, B = 3;
movesRequired(A, B);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void movesRequired( int a, int b)
{
int total_moves = a % b;
System.out.println(total_moves);
}
public static void main(String[] args)
{
int A = 10 , B = 3 ;
movesRequired(A, B);
}
}
|
Python3
def movesRequired(a, b):
total_moves = a % b
print (total_moves)
if __name__ = = '__main__' :
A = 10
B = 3
movesRequired(A, B)
|
C#
using System;
class GFG
{
static void movesRequired( int a, int b)
{
int total_moves = a % b;
Console.Write(total_moves);
}
public static void Main(String []args)
{
int A = 10, B = 3;
movesRequired(A, B);
}
}
|
Javascript
<script>
function movesRequired(a, b)
{
let total_moves = a % b;
document.write(total_moves);
}
let A = 10, B = 3;
movesRequired(A, B);
</script>
|
Time Complexity: O(1), as constant operations are being performed.
Auxiliary Space: O(1), constant space is required for the above approach.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
06 Sep, 2022
Like Article
Save Article