Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?
I'm studying C++ and x86 assembly, and I decided to write a program to test the Collatz conjecture (3n+1). The idea is simple: take a number, if it's even — divide by 2, if it's odd — multiply by 3 and add 1. You need to count how many steps it takes to reach 1.
First I wrote the code in C++:
```cpp
int collatz(int n) {
int steps = 0;
while (n != 1) {
if (n % 2 == 0)
n /= 2;
else
n = 3 * n + 1;
steps++;
}
return steps;
}
```
Then I manually wrote an assembly version using x86-64 instructions, thinking it would be faster:
```asm
collatz_asm:
xor eax, eax ; steps = 0
.loop:
cmp edi, 1
je .done
test edi, 1
jnz .odd
shr edi, 1 ; even: n /= 2
inc
```