Assembly 整数的平方根,为什么这样做?
大家早上好,今天我看到了一个计算整数平方根的聪明方法。虽然它确实有效,但我不明白它为什么有效。 以下是代码:Assembly 整数的平方根,为什么这样做?,assembly,square-root,Assembly,Square Root,大家早上好,今天我看到了一个计算整数平方根的聪明方法。虽然它确实有效,但我不明白它为什么有效。 以下是代码: mov output, 0 mov eax, input mov ebx, 1 loop: sub eax, ebx cmp eax, 0 jl end inc output add ebx, 2 jmp loop end: 现在请注意我的问题,我知道这是如何工作的:它通过不均匀的数字(1,3,5,7…)减少输入,如果输入仍然大于等于0,它将输出增加1并重复该过程,
mov output, 0
mov eax, input
mov ebx, 1
loop:
sub eax, ebx
cmp eax, 0
jl end
inc output
add ebx, 2
jmp loop
end:
现在请注意我的问题,我知道这是如何工作的:它通过不均匀的数字(1,3,5,7…)减少输入,如果输入仍然大于等于0,它将输出增加1并重复该过程,否则输出是输入的整数平方根。我不知道这个算法工作的原因,我在问是否有人知道它。要生成I=1到n的(2i-1)的和,请颠倒数字并加上:
1 + 3 + 5 + 7 + ... + 2n-3 + 2n-1
+ 2n-1 + 2n-3 + 2n-5 + 2n-7 + ... + 3 + 1
----------------------------------------------
2n + 2n + 2n + 2n + ... + 2n + 2n
=2n^2,但由于总和加了两次,除以2,所以
对于i=1到n的(2i-1)=n^2的和。注意1=1,1+3=4,1+3+5=9。。。一般来说,前n个奇数的和是n^2。这是一个非常常见的系列