Find the number closest to n and divisible by m in C++

C++Server Side ProgrammingProgramming

Suppose we have two integers n and m. We have to find the number closest to n and divide by m. If there are more than one such number, then show the number which has maximum absolute value. If n is completely divisible by m, then return n. So if n = 13, m = 4, then output is 12.

To solve this, we can follow this steps −

  • let q := n/m, and n1 := m*q
  • if n * m > 0, then n2 := m * (q + 1), otherwise n2 := m * (q - 1)
  • if |n – n1| < |n – n2|, then return n1, otherwise n2

Example

 Live Demo

#include<iostream>
#include<cmath>
using namespace std;
int findClosest(int n, int m) {
   int q = n / m;
   int n1 = m * q;
   int n2 = (n * m) > 0 ? (m * (q + 1)) : (m * (q - 1));
   if (abs(n - n1) < abs(n - n2))
      return n1;
   return n2;
}
int main() {
   int n = 13, m = 4;
   cout << "Closest for n = " << n << ", and m = " << m << ": " << findClosest(n, m) << endl;
      n = 0; m = 8;
   cout << "Closest for n = " << n << ", and m = " << m << ": " << findClosest(n, m) << endl;
      n = 18; m = -7;
   cout << "Closest for n = " << n << ", and m = " << m << ": " << findClosest(n, m) << endl;
}

Output

Closest for n = 13, and m = 4: 12
Closest for n = 0, and m = 8: 0
Closest for n = 18, and m = -7: 21
raja
Published on 19-Dec-2019 07:12:24
Advertisements