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?
try this (Requires INTEGER division):
7/3 = 2. 3*(2+1) = 9.
You have an edge case where the
baseNumber
already is a multiple ofnumber
, which you will have to test using the modulus operation.If everything is guaranteed to be positive, try
That does it in constant time.
First, we add
number - 1
to 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 bynumber
to make sure we have the desired multiple.If
baseNumber
can be negative (butnumber
still positive), we face the problem thatmultiple % number
may 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
if
at the cost of two divisions instead of one,Generally, the
if
seems preferable, though.If
number
can be negative, replace it with its absolute value first.Note: The above returns, as the original code does,
baseNumber
if that is already a multiple ofnumber
. If that isn't desired, remove the- 1
in the first line.Why do you need a loop?
multiple = (floor(number/baseNumber)+1)*baseNumber
so for baseNumber = 3, number = 7, your multiple is 3;
though, something tells me bignums are about to show up in here.