Multiple of x closest to n
Given two numbers n and x, we need to calculate the smallest value of x that is closest to given number n.
Examples:
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
We need to find a k such that x*k is closest to n. If we do k = n/x, we get a value of k that may not lead to maximum. We can get closest by comparing the values floor(n/x) * x and ceil(n/x) * x.
Below is an interesting solution that doesn’t require computations of floor(n/x) and ceil(n/x). The idea is to do following two steps.
n = n + x/2;
n = n - (n%x);
result = n
Let us consider below example
n = 2855
x = 13
n = 2855 + 13/2
= 2861
n = 2861 - (2861 % 13)
= 2861 - 1
= 2860
Below are implementations of above steps.
C++
#include <bits/stdc++.h>
using namespace std;
int closestMultiple( int n, int x)
{
if (x>n)
return x;
n = n + x/2;
n = n - (n%x);
return n;
}
int main()
{
int n = 9, x = 4;
printf ( "%d" , closestMultiple(n, x));
return 0;
}
|
Java
import java.io.*;
class Solution
{
static int closestMultiple( int n, int x)
{
if (x>n)
return x;
n = n + x/ 2 ;
n = n - (n%x);
return n;
}
public static void main (String[] args)
{
int n = 56287 , x = 27 ;
System.out.println(closestMultiple(n, x));
}
}
|
Python3
def closestMultiple(n, x):
if x > n:
return x;
z = ( int )(x / 2 );
n = n + z;
n = n - (n % x);
return n;
n = 56287 ;
x = 27 ;
print (closestMultiple(n, x));
|
C#
using System;
class Solution {
static int closestMultiple( int n, int x)
{
if (x > n)
return x;
n = n + x / 2;
n = n - (n % x);
return n;
}
public static void Main()
{
int n = 56287, x = 27;
Console.WriteLine(closestMultiple(n, x));
}
}
|
PHP
<?php
function closestMultiple( $n , $x )
{
if ( $x > $n )
return $x ;
$n = $n + $x / 2;
$n = $n - ( $n % $x );
return $n ;
}
$n = 9;
$x = 4;
echo closestMultiple( $n , $x );
?>
|
Javascript
<script>
function closestMultiple(n, x)
{
if (x > n)
return x;
n = n + parseInt(x / 2, 10);
n = n - (n % x);
return n;
}
let n = 56287, x = 27;
document.write(closestMultiple(n, x));
</script>
|
Time Complexity: O(1)
As we are performing only constant time operations.
Auxiliary Space: O(1)
As constant extra space is used.
Last Updated :
16 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...