
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Find the number closest to 10000 and divisible by 30 , 45 , 15.
- Replace m by smallest whole number to make the number resulting number divisible\n46 m 46 (by 3)
- Find N digits number which is divisible by D in C++
- Find the closest and smaller tidy number in C++
- N digit numbers divisible by 5 formed from the M digits in C++
- Count n digit numbers divisible by given number in C++
- Greatest number divisible by n within a bound in JavaScript
- Program to find remainder after dividing n number of 1s by m in Python
- JavaScript Program to Find closest number in array
- Find permutation of n which is divisible by 3 but not divisible by 6 in C++
- C# Program to find whether the Number is Divisible by 2
- Find the largest 4 digit number divisible by 16.
- Smallest possible number divisible by all numbers from 1 to n in JavaScript
- Largest number smaller than or equal to N divisible by K in C++
- Find the least number divisible by 15, 20, 24, 32, and 36.

Advertisements