aboutsummaryrefslogtreecommitdiffstats
path: root/02-Even-Fibonacci-numbers/asm/fib.asm
blob: 600a54209e404a448dc3a98a0594bad1df4a553a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
; By considering the terms in the Fibonacci sequence whose values do not exceed four million,
; find the sum of the even-valued terms.
extern printf
SECTION .data
flag:   db  "%d",10,0           ; "%d\n\0"

SECTION .text
    global main    

main:
        push rbp                ; set up stack
        mov rbp, rsp
        mov rax, 1              ; start at fib_1 = 1
        push rax                ; push first term of fib onto stack
        mov r11, 0              ; sum = 0
        mov r12, 0x3D0900       ; max = 4000000, this is < 2^64
                                ; so we only need one register

.loop   xor rdx, rdx            ; clear rdx (remainder) 
        push rax                ; push current term on the stack
        mov rcx, 2              ; divisible by 2
        div rcx                 ; divide rdx:rax/rcx
        cmp rdx, 0              ; compare only remainder
        jz .sum                 ; if r = 0 , add to sum
        jmp .next               ; else skip

.sum    add r11, QWORD [rsp]    ; add latest term to sum register

.next   mov rax, QWORD [rsp]    ; reload rax to current term                
        add rax, QWORD [rsp+8]  ; add last term to current term
        cmp rax, r12            ; while rax < r12 (4 mil)
        jl .loop
        
        mov rdi, flag           ; arg 1 (format)
        mov rsi, r11            ; arg 2 (value)
        mov rax, 0		; no xmm registers
        call printf wrt ..plt
        mov rsp, rbp            ; reset to the top of the stack
        pop rbp

        mov rax, 0
        ret