📌  相关文章
📜  一定范围内要添加的最小元素,以使元素数可被K整除

📅  最后修改于: 2021-05-06 21:22:35             🧑  作者: Mango

给定三个整数KLR (范围[L,R] ),任务是找到必须扩展范围的最小元素数,以使范围中的元素数可被K整除。

例子:

方法:

  • 计算范围内的元素总数,并将其存储在名为count = R – L + 1的变量中。
  • 现在,需要添加到范围中的最小元素数将为K –(计数%K)。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
int minimumMoves(int k, int l, int r)
{
    // Total elements in the range
    int count = r - l + 1;
  
    // If total elements are already divisible by k
    if (count % k == 0)
        return 0;
  
    // Value that must be added to count
    // in order to make it divisible by k
    return (k - (count % k));
}
  
// Driver Program to test above function
int main()
{
    int k = 3, l = 10, r = 10;
    cout << minimumMoves(k, l, r);
  
return 0;
}


Java
// Java implementation of the approach
  
import java.io.*;
  
class GFG {
     
 static int minimumMoves(int k, int l, int r)
{
    // Total elements in the range
    int count = r - l + 1;
  
    // If total elements are already divisible by k
    if (count % k == 0)
        return 0;
  
    // Value that must be added to count
    // in order to make it divisible by k
    return (k - (count % k));
}
  
// Driver Program to test above function
    public static void main (String[] args) {
    int k = 3, l = 10, r = 10;
    System.out.print(minimumMoves(k, l, r));
    }
}
// This code is contributed 
// by inder_verma..


Python3
# Python 3 implementation of the approach
  
def minimumMoves(k, l, r):
    # Total elements in the range
    count = r - l + 1
  
    # If total elements are already divisible by k
    if (count % k == 0):
        return 0
  
    # Value that must be added to count
    # in order to make it divisible by k
    return (k - (count % k))
  
# Driver Program to test above function
if __name__ == '__main__':
    k = 3
    l = 10
    r = 10
    print(minimumMoves(k, l, r))
  
# This code is contributed by
# Surendra_Gangwar


C#
// C# implementation of the approach
using System;
  
class GFG {
      
  
  
static int minimumMoves(int k, int l, int r)
{
    // Total elements in the range
    int count = r - l + 1;
  
    // If total elements are already divisible by k
    if (count % k == 0)
        return 0;
  
    // Value that must be added to count
    // in order to make it divisible by k
    return (k - (count % k));
}
  
// Driver Program to test above function
    public static void Main () {
    int k = 3, l = 10, r = 10;
    Console.WriteLine(minimumMoves(k, l, r));
    }
}
// This code is contributed 
// by inder_verma..


PHP


输出:
2