aboutsummaryrefslogtreecommitdiffstats
path: root/05-Smallest-Multiple/asm/smallmult.asm
blob: c154ff37258a0fa6198d4a234c43c08f00443495 (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
44
; 2520 is the smallest number that can be divided by each of the numbers 
; from 1 to 10 without any remainder.
; What is the smallest positive number that is evenly divisible by all 
; of the numbers from 1 to 20?

extern printf
SECTION .data
flag:   db  "%d",10,0           ; "%d\n\0"

SECTION .text
    global main    
    global is_divisible

main:
        push rbp                ; set up stack
        mov rbp, rsp

        mov rax, 2520           ; value to start at (given)
        mov rcx, 20             ; divisor (counting down)
.loop   add rax, rcx
        push rcx
.isdiv  xor rdx, rdx            ; clear rdx for div
        push rax                ; save rax before dividing
        div rcx                 ; rdx:rax/rcx = rax remainder rdx
        pop rax                 ; reload rax to be divided again
        cmp rdx, 0              ; the number was divisible, keep going
        loopz .isdiv            ; loop exits if rdx is non zero OR rcx is 0
        cmp rcx, 0              ; if rcx = 0, it means it looped 20 to 1 w/o
        jz .print               ; any remainders, that's our number!
        ; if you get here, number couldn't be evenly divided by all numbers
        pop rcx
        jmp .loop



.print: mov rdi, flag           ; arg 1 (format)
        mov rsi, rax            ; arg 2 (value)
        mov rax, 0		; no xmm registers
        call printf wrt ..plt
        pop rbp

        mov rax, 0
        ret