r******e 发帖数: 80 | 1 Given integer n and m, is there a fast way to calculate n*m or n/m using
only 'add' operation?
a straightforward way to calculate n*m and n/m is to add m times of n and
add multiple times of -m. Not sounds optimization enough. Any idea?
Thanks a lot. |
l*****a 发帖数: 559 | 2 There exists logarithmic way to do this job.
int divide(int a,int b){
int res = 0;
int digit = 1;
while(b<<1<=a){
b = b<<1;
digit = digit<<1;
}
while(digit>0&&a>0){
if(a>=b){
res +=digit;
a-=b;
}
b>>=1;
digit>>=1;
}
return res;
} |
i***1 发帖数: 95 | 3 awesome!
【在 l*****a 的大作中提到】 : There exists logarithmic way to do this job. : int divide(int a,int b){ : int res = 0; : int digit = 1; : while(b<<1<=a){ : b = b<<1; : digit = digit<<1; : } : while(digit>0&&a>0){ : if(a>=b){
|
r******e 发帖数: 80 | 4 看了半天, 不明白为什么。 楼主能不能把原理解释一下? 非常感谢 |