Minimum positive integer divisible by C and is not in range [A, B] in C++

C++Server Side ProgrammingProgramming

Suppose we have three integers A, B, and C. We have to find one minimum integer X, such that X mod C = 0, and X is not in the range [A, B]. If the values of A, B and C are 5, 10 and 4 respectively, then the value of X will be 4. Let us see the steps to get the solution −

Steps

  • If C is not in the range [A, B], then return C as a result
  • Otherwise get the first multiple of C, which is greater than B, then return that value

Example

 Live Demo

#include <iostream>
using namespace std;
int findMinMumber(int a, int b, int c) {
   if (c < a || c > b)
   return c;
   int res = ((b / c) * c) + c;
   return res;
}
int main() {
   int a = 2, b = 4, c = 2;
   cout << "Minimum number X: " << findMinMumber(a, b, c);
}

Output

Minimum number X: 6
raja
Published on 21-Oct-2019 11:04:59
Advertisements