我想在汇编中实现 Collatz 猜想。它的算法应该计算需要多少步,直到 EAX 的值变为 1。但是我有问题,当我尝试执行时,控制台显示“Core Dumped”或者它卡住。我将步数存储在 EBX 中。我在程序的主要部分通过 push eax
call f
pop eax
调用此函数。
f:
mov eax, [esp+4]
cmp eax,1
je end
AND eax, 0x01
jz parity
inc ebx
imul eax,3
inc eax
parity:
inc ebx
shr eax,1
jmp f
end:
mov eax,ebx
ret
请帮忙
更新
已解决。
f:
mov eax, [esp+4]
mov ebx, 1 ;In case EAX=1 !!!
jjump:
cmp eax,1
je end
test eax, 0x01
jz parity
inc ebx
imul eax,3
inc eax
jmp jjump
parity:
inc ebx
shr eax,1
jmp jjump
end:
mov eax,ebx
ret
最佳答案
你写了一个无限循环。如果 [esp+4] 处的值不是 1,您总是跳回标签 f 并重新读取相同的值!
将标签放在这里:
f:
mov eax, [esp+4]
f_:
您可能应该test eax, 1
而不是and
,因为后者会破坏您想要继续使用的值。
两种可能性都必须跳转到额外标签jjump
jmp jjump
parity:
整个代码变为:
f:
mov eax, [esp+4]
mov ebx, 1 ;In case EAX=1 !!!
jjump:
cmp eax,1
je end
test eax, 0x01
jz parity
inc ebx
imul eax,3
inc eax
jmp jjump
parity:
inc ebx
shr eax,1
jmp jjump
end:
mov eax,ebx
ret
关于assembly - Collatz 猜想程序中的核心被转储到 Assembly 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256771/