CoCubes Programming Questions – 4
Find the number closest to n and divisible by m
Given two integers n and m. The problem is to find the number closest to n and divisible by m. If there are more than one such number, then output the one having maximum absolute value. If n is completely divisible by m, then output n only. Time complexity of O(1) is required.
Constraints: m != 0
We find value of n/m. Let this value be q. Then we find closest of two possibilities. One is q * m other is (m * (q + 1)) or (m * (q – 1)) depending on whether one of the given two numbers is negative or not.
Algorithm:
closestNumber(n, m) Declare q, n1, n2 q = n / m n1 = m * q if (n * m) > 0 n2 = m * (q + 1) else n2 = m * (q - 1) if abs(n-n1) < abs(n-n2) return n1 return n2
C++
Java
C++
#include <bits/stdc++.h> using namespace std; int closestNumber (int n, int m) { // find the quotient int q = n / m; // 1st possible closest number int n1 = m * q; // 2nd possible closest number int n2 = (n * m) > 0 ? (m * (q + 1)) : (m * (q - 1)); // if true, then n1 is the required closest number if (abs (n - n1) < abs (n - n2)) return n1; // else n2 is the required closest number return n2; } int main () { int n, m; cout<< "Enter the two numbers\n"; cin>> n; cin>> m; cout << closestNumber (n, m) << endl; return 0; }
Java
import java.util.*; class Main { // function to find the number closest to n // and divisible by m static int closestNumber (int n, int m) { // find the quotient int q = n / m; // 1st possible closest number int n1 = m * q; // 2nd possible closest number int n2 = (n * m) > 0 ? (m * (q + 1)) : (m * (q - 1)); // if true, then n1 is the required closest number if (Math.abs (n - n1) < Math.abs (n - n2)) return n1; // else n2 is the required closest number return n2; } // Driver program to test above public static void main (String args[]) { Scanner sc=new Scanner (System.in); int n=sc.nextInt(); int m=sc.nextInt(); System.out.println (closestNumber (n, m)); } }
n,m=map(int,input().split())
q=n//m
n1=q*m
n2=n1
if (n*m)>0:
n2=m*(q+1)
else:
n2=m*(q-1)
if abs(n-n1)<abs(n-n2):
print(n1)
else:
print(n2)
PYTHON 3.8
n= int(input())
m= int(input())
div = n//m
print(div*m)
n,m=map(int,input().split())
print(round((n/m))*m)
Direct answer
round((float)n/m)*m
Cocubes Coding Questions