I am trying to code the collatz problem in assembly (just for fun). I just finished the first part. I am calling the assembly code from a C++ function in a different file:
if (((n / 2) * 2) == n) n = n / 2;
else n = 3 * n + 1;
.code
isCN proc n:dword
mov eax, n
xor edx, edx
mov ecx, 2
mov r8d, eax
div ecx
mov r9d, eax
mul ecx
cmp eax, r8d
je equal
;else
mov eax, 3
mul r8d
add eax, 1
ret
equal:
; if n is even
mov eax, r9d
ret
isCN ENDP
end
I am using the code like that:
extern "C" int isCN(int n);
while (n > 1) {
c++;
n = isCN(n);
}
validNumbers[i] = true;
counters[i] = c;
But when I try to use it, the value it returns is nonsense.
When I look at the disassembly, it seems to be correctly returned from eax
.
Is the error in the way I use the code, or in the code itself?
Your code is inefficient but from a quick test it does seem to work. A more efficient version could be:
mov eax, ecx
shr eax, 1
jnc done
lea eax, [2*ecx + ecx + 1]
done:
ret
(Assuming you are using windows calling convention.)