The register shuffle in Assembly
Fibonacci in three registers, no memory at all.
; Fibonacci in three registers: the classic register shuffle.
global _start
section .text
_start:
xor rax, rax ; fib(0)
mov rbx, 1 ; fib(1)
mov rcx, 10 ; steps to take
.step:
mov rdx, rax
add rdx, rbx ; next = a + b
mov rax, rbx ; a = b
mov rbx, rdx ; b = next
dec rcx
jnz .step
mov rdi, rax ; fib(10) = 55
mov rax, 60 ; exit code 55
syscall
How it works
- Two registers hold the pair; a third stages the sum.
- The rotation a=b, b=next advances the sequence.
- Ten steps land on fib(10) = 55.
Keywords and builtins used here
adddecglobaljnzmovraxrbxrcxrdirdxsectionsyscallxor
The run, in numbers
- Lines
- 19
- Characters to type
- 435
- Tokens
- 56
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 56 seconds.
Step 4 of 4 in Memory & strings, step 25 of 31 in Language basics.