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.