Minimum elements to be added in a range so that count of elements is divisible by K
Given three integer K, L and R (range [L, R]), the task is to find the minimum number of elements the range must be extended by so that the count of elements in the range is divisible by K.
Examples:
Input: K = 3, L = 10, R = 10
Output: 2
Count of elements in L to R is 1.
So to make it divisible by 3 , increment it by 2.
Input: K = 5, L = 9, R = 12
Output: 1
Approach:
- Count the total number of elements in the range and store it in a variable named count = R – L + 1.
- Now, minimum number of elements that need to be added to the range will be K – (count % K).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimumMoves( int k, int l, int r)
{
int count = r - l + 1;
if (count % k == 0)
return 0;
return (k - (count % k));
}
int main()
{
int k = 3, l = 10, r = 10;
cout << minimumMoves(k, l, r);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int minimumMoves( int k, int l, int r)
{
int count = r - l + 1 ;
if (count % k == 0 )
return 0 ;
return (k - (count % k));
}
public static void main (String[] args) {
int k = 3 , l = 10 , r = 10 ;
System.out.print(minimumMoves(k, l, r));
}
}
|
Python3
def minimumMoves(k, l, r):
count = r - l + 1
if (count % k = = 0 ):
return 0
return (k - (count % k))
if __name__ = = '__main__' :
k = 3
l = 10
r = 10
print (minimumMoves(k, l, r))
|
C#
using System;
class GFG {
static int minimumMoves( int k, int l, int r)
{
int count = r - l + 1;
if (count % k == 0)
return 0;
return (k - (count % k));
}
public static void Main () {
int k = 3, l = 10, r = 10;
Console.WriteLine(minimumMoves(k, l, r));
}
}
|
PHP
<?php
function minimumMoves( $k , $l , $r )
{
$count = $r - $l + 1;
if ( $count % $k == 0)
return 0;
return ( $k - ( $count % $k ));
}
$k = 3; $l = 10; $r = 10;
echo minimumMoves( $k , $l , $r );
?>
|
Javascript
<script>
function minimumMoves(k, l, r)
{
let count = r - l + 1;
if (count % k == 0)
return 0;
return (k - (count % k));
}
let k = 3, l = 10, r = 10;
document.write(minimumMoves(k, l, r));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
08 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...