- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

#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

- Related Questions & Answers
- N digit numbers divisible by 5 formed from the M digits in C++
- Find N digits number which is divisible by D in C++
- Find a positive number M such that gcd(N^M,N&M) is maximum in Python
- Program to find remainder after dividing n number of 1s by m in Python
- Find the largest number with n set and m unset bits in C++
- Count of m digit integers that are divisible by an integer n in C++
- Find the closest and smaller tidy number in C++
- Count n digit numbers divisible by given number in C++
- Greatest number divisible by n within a bound in JavaScript
- Find permutation of n which is divisible by 3 but not divisible by 6 in C++
- Find the minimum number of steps to reach M from N in C++
- C# Program to find whether the Number is Divisible by 2
- Print all the combinations of N elements by changing sign such that their sum is divisible by M in C++
- Generating a random number that is divisible by n in JavaScript
- Smallest number that is divisible by first n numbers in JavaScript

Advertisements