在汇编 x86 中计算 LCM [英] Calculating LCM in assembly x86
问题描述
我有以下汇编代码
.global _start
.section .text
_start:
movq a, %rax
movq b, %rbx
imul %rbx, %rax
cmp %rbx, %rax
je gcd_calculated
ja l1
sub %rax, %rbx
jmp _start
l1:
sub %rbx, %rax
jmp _start
gcd_calculated:
div %rax
movq %rax, (c)
a,b
是我需要计算它们的 lcm 的四边形,我需要将结果分配给 c
a,b
are quads that I need to calculate their lcm and I need to assign the result to c
我在上面的代码中得到错误的结果,我不知道为什么.
I get wrong results with the above code and I can't spot why.
通常,我在 lcm = (a*b)/gcd
上中继,所以我将 a*b 存储在 %rax
中,然后计算 gcd将存储在 %eax 并最终在它们之间进行划分.
generally, i'm relaying on the the lcm = (a*b)/gcd
so I store a*b in %rax
and then calculate the gcd which will be stored at %eax and finally divide between them.
推荐答案
就像 1201ProgramAlarm 说的,你在每次迭代中计算和比较 a
和 b
的原始值你的循环.如果您想遵循当前的方法,则必须在每次循环之前将这些值存储在内存中.
Like 1201ProgramAlarm said, you are calculating and comparing the original values of a
and b
in each iteration of your loop. If you want to follow your current approach, you would have to store these values in memory each time before looping.
我实际上要做的只是先进行 gcd 计算,然后在最后计算 (a*b)/gcd
.
What I would actually do instead is just do the gcd calculation first and then calculate (a*b)/gcd
at the end.
_start:
movq a(%rip), %rbx
movq b(%rip), %rcx
gcd:
cmp %rbx, %rcx
je gcd_calculated
ja l1
sub %rcx, %rbx
jmp gcd
l1:
sub %rbx, %rcx
jmp gcd
gcd_calculated:
movq a(%rip), %rax
xor %rdx, %rdx
div %rbx
imul b(%rip), %rax
movq %rax, c(%rip)
这篇关于在汇编 x86 中计算 LCM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!