1

I'm trying to design a function int smallestDivisibleAfter(int number, int divisor) such that it returns the smallest number greater than or equal to number that is divisible by divisor (which is non-zero) . Here all inputs and outputs are assumed to be non-negative.

Examples:

smallestDivisibleAfter(9,4); // Returns 12
smallestDivisibleAfter(16,2); // Returns 16

I came up with the code number + divisor - number % divisor. However this ceases to work when number % divisor == 0, since then smallestDivisibleAfter(16,2); // Returns 18 instead of 16.

In addition, number - 1 + divisor - (number - 1)% divisor does not work since int will be replaced by unsigned long long when I put this code into action.

What is the best solution here?

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
Henricus V.
  • 898
  • 1
  • 8
  • 29

2 Answers2

1

If you want to avoid jumps, try:

number - number % divisor + divisor * !!(number % divisor)

The !!x just converts the number to a boolean with 0 if x==0 and 1 otherwise.

Juan Lopes
  • 10,143
  • 2
  • 25
  • 44
-2
((number / divisor)  + 1) * divisor)

This will return the next greatest multiple of divisor after number.

If you ever plan on using floats: floor(number / divisor).

  • Integer division doesn't result in a float; there's nothing to floor(). – m69's been on strike for years Apr 12 '16 at 00:25
  • 2
    A small suggestion: it's better to gain confidence in your answer before publishing it. The goal of answering isn't to guess the right answer as quickly as possible, it's to provide a correct and convincing answer that other people can read and understand. – Paul Hankin Apr 12 '16 at 00:27
  • Yeah I just edited that, originally I didn't bother with floor then added it in casehe decides to use floats – user6190774 Apr 12 '16 at 00:27
  • This is not correct because if `number` is already divisible by `divisor` it will return `number + divisor`. – Lars M. Jun 22 '19 at 07:42