📜  x最接近n的倍数

📅  最后修改于: 2021-05-05 00:57:03             🧑  作者: Mango

给定两个数字n和x,我们需要计算最接近给定数字n的x的最小值。

例子:

Input : n = 9, x = 4
Output : 8

Input  : n = 2855, x = 13
Output : 2860

Input  :  n = 46426171, x = 43
Output :  46426154

Input  :  n = 1, x = 3
Output :  3

我们需要找到使得x * k最接近n的ak。如果我们做k = n / x,我们得到的k值可能不会导致最大值。我们可以通过比较值floor(n / x)* x和ceil(n / x)* x来获得最接近的值。

下面是一个有趣的解决方案,不需要计算floor(n / x)和ceil(n / x)。这个想法是按照以下两个步骤进行的。

n = n + x/2;
    n = n - (n%x);
    result = n

让我们考虑下面的例子

n = 2855 
  x = 13

  n = 2855 + 13/2
    = 2861
  n = 2861 - (2861 % 13)
    = 2861 - 1
    = 2860 

以下是上述步骤的实现。

C++
// CPP program to calculate the smallest multiple
// of x closest to a given number
#include 
using namespace std;
  
// Function to calculate the smallest multiple
int closestMultiple(int n, int x)
{   
    if(x>n)
       return x;
  
    n = n + x/2;
    n = n - (n%x);
    return n;
}
  
// driver program
int main()
{
    int n = 9, x = 4;
    printf("%d", closestMultiple(n, x));
    return 0;
}


Java
// Java program to calculate the smallest 
// multiple of x closest to a given number
import java.io.*;
class Solution
{
    // Function to calculate the smallest multiple
    static int closestMultiple(int n, int x)
    {   
        if(x>n)
           return x;
        n = n + x/2;
        n = n - (n%x);
        return n;
    }
  
    // driver program
    public static void main (String[] args) 
    {
        int n = 56287, x = 27;
        System.out.println(closestMultiple(n, x));
    }
}


Python3
# Python3 program to calculate 
# the smallest multiple of x 
# closest to a given number
  
# Function to calculate
# the smallest multiple
def closestMultiple(n, x):
    if x > n:
        return x;
    z = (int)(x / 2);
    n = n + z;
    n = n - (n % x);
    return n;
  
# Driver Code
n = 56287;
x = 27;
print(closestMultiple(n, x));
  
# This code is contributed
# by mits


C#
// C# program to calculate smallest
// multiple of x closest to a
// given number
using System;
  
class Solution {
    // Function to calculate the
    // smallest multiple
    static int closestMultiple(int n, int x)
    {
  
        if (x > n)
            return x;
        n = n + x / 2;
        n = n - (n % x);
        return n;
    }
  
    // Driver program
    public static void Main()
    {
        int n = 56287, x = 27;
        Console.WriteLine(closestMultiple(n, x));
    }
}
  
// This code is contributed by Anant Agarwal.


PHP
 $n)
    return $x;
  
    $n = $n + $x / 2;
    $n = $n - ($n % $x);
    return $n;
}
  
    // Driver Code
    $n = 9;
    $x = 4;
    echo closestMultiple($n, $x);
      
// This code is contributed by ajit
?>


输出:

56295