问题
We had an assignment where we had to write the collatz conjecture in 64bit nasm assembly with only 13 commands or less (RET included). Now we are wondering how much you can actually reduce it. We are currently on 9.
Heres the collatz conjecture in pseudo code for reference:
Heres the code we have so far. A few notes:
A tutor of us said we can remove the XOR rax, rax because of some calling convention it's already zero. It doesn't work on my computer though so I've included it here.
I'm aware the two LEA's are probably the most obvious thing to reduce, but we can't think of a way since *6 seems to be the only thing thats literally impossible to do with LEA.
GLOBAL collatz
SECTION .text
collatz:
XOR rax, rax
.while:
SHR rdi, 1
JNC .even
LEA rdi, [rdi*2+1]
LEA rdi, [rdi*2+rdi+1]
.even:
INC rax
CMP rdi, 1
JA .while
RET
回答1:
This is somewhat shorter:
collatz:
or $-1,%eax
.loop: inc %eax
lea 1(%rdi,%rdi,2),%rsi
shr %rdi
cmovc %rsi,%rdi
jnz .loop
ret
or, in nasm syntax:
collatz:
or eax,-1
.loop: inc eax
lea rsi,[rdi+rdi*2+1]
shr rdi
cmovc rdi,rsi
jnz .loop
ret
To understand this code, pay close attention to the carry flag (CF) and zero flag (ZF).
来源:https://stackoverflow.com/questions/42149201/collatz-conjecture-in-assembly-shortest-form