I need to find the first multiple for a number starting from a base number. For example: The first multiple of 3 from 7 is 9. My first attempt was to do this:
multiple = baseNumber
while(multiple%number !=0 )
multiple++
At the end, “multiple” will have the first multiple of number after baseNumber. The problem is that when number becomes too large, the number of iterations becomes too many. So my question is: is there a faster way to do this?
If everything is guaranteed to be positive, try
That does it in constant time.
First, we add
number - 1to make sure that we have a number at least as large as the next multiple but smaller than the one after that. Then we subtract the remainder of the division bynumberto make sure we have the desired multiple.If
baseNumbercan be negative (butnumberstill positive), we face the problem thatmultiple % numbermay be negative ifmultiple < 0, so the above could skip a multiple ofnumber. To avoid that, we can use e.g.If branching is too expensive, we can avoid the
ifat the cost of two divisions instead of one,Generally, the
ifseems preferable, though.If
numbercan be negative, replace it with its absolute value first.Note: The above returns, as the original code does,
baseNumberif that is already a multiple ofnumber. If that isn’t desired, remove the- 1in the first line.