快速的方式找到一个数的倍数 [英] Fast way to find the next multiple of a number
问题描述
我需要找到从基数开始数的第一个倍数。例如:3 7的第一个多是9.我第一次尝试这样做:
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++
最后,多重将有数量
后 baseNumber
第一多个。的问题是,当号
变得过大,迭代的数量变得过多。所以我的问题是:有没有更快的方法来做到这一点。
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?
推荐答案
尝试
multiple = baseNumber + number - 1;
mutliple -= (multiple % number);
这确实是在固定时间内。
That does it in constant time.
首先,我们添加 - 1
,以确保我们有一个数字至少应为下一个倍数,但比后一小。然后,我们通过数量
减去的余数,以确保我们有所需的倍数。
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 by number
to make sure we have the desired multiple.
注:以上的回报,因为原来的code呢, baseNumber
如果这已经是数的倍数
。如果这是不希望的,删除 - 1
在第一行
Note: The above returns, as the original code does, baseNumber
if that is already a multiple of number
. If that isn't desired, remove the - 1
in the first line.
这篇关于快速的方式找到一个数的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!