Smallest number required to be added to M to make it divisible by N
Last Updated :
09 Jun, 2021
Given two positive integers M and N, the task is to calculate the smallest number that needs to be added to M, to make it divisible by N.
Examples:
Input: M = 6, N = 7
Output: 1
Explanation: 1 is the smallest number that can be added to 6 to make it divisible by 7.
Input: M = 100, N = 28
Output: 12
Approach: The idea is to find the smallest number greater than or equal to M, that is divisible by N, and then subtract M from it. To get the smallest multiple of N ? M, divide M + N by N. If the remainder is 0, then the value is M. Otherwise, the value is M + N – remainder.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findNum( int N, int K)
{
int rem = (N + K) % K;
if (rem == 0)
return N;
else
return N + K - rem;
}
int findSmallest( int M, int N)
{
int x = findNum(M, N);
return x - M;
}
int main()
{
int M = 100, N = 28;
cout << findSmallest(M, N);
return 0;
}
|
Java
class GFG{
public static int findNum( int N, int K)
{
int rem = (N + K) % K;
if (rem == 0 )
return N;
else
return N + K - rem;
}
public static int findSmallest( int M, int N)
{
int x = findNum(M, N);
return x - M;
}
public static void main(String args[])
{
int M = 100 , N = 28 ;
System.out.println(findSmallest(M, N));
}}
|
Python3
def findNum(N, K):
rem = (N + K) % K
if (rem = = 0 ):
return N
else :
return N + K - rem
def findSmallest(M, N):
x = findNum(M, N)
return x - M
if __name__ = = '__main__' :
M = 100
N = 28
print (findSmallest(M, N))
|
C#
using System;
class GFG{
public static int findNum( int N, int K)
{
int rem = (N + K) % K;
if (rem == 0)
return N;
else
return N + K - rem;
}
public static int findSmallest( int M, int N)
{
int x = findNum(M, N);
return x - M;
}
public static void Main()
{
int M = 100, N = 28;
Console.WriteLine(findSmallest(M, N));
}
}
|
Javascript
<script>
function findNum(N, K)
{
var rem = (N + K) % K;
if (rem == 0)
return N;
else
return N + K - rem;
}
function findSmallest(M, N)
{
var x = findNum(M, N);
return x - M;
}
var M = 100, N = 28;
document.write(findSmallest(M, N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...