Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

ITT we optimize fizzbuzz

Name: Anonymous 2009-05-24 0:16

Here's a pretty basic version in NASM style x86 assembly on linux:
; Fizzbuzz in nasm Linux x86 Assembler

; Prints a natural number onto stdout
%macro    printnumber 1
    pushad

    ; initializations in case of witchcraft
    mov    eax, %1
    mov    ebx, 10
    xor    ecx, ecx

    ; puts digits of number onto stack with first on top
    generate:
    cmp    eax, 0
    je    print
    xor    edx, edx
    div    ebx
    push     edx
    inc    ecx
    jmp    generate
   
    ; pulls digits out of stack and prints them
    print:
    pop     edx
    push     ecx
    ; potential optimization: figure out how to print immediate numbers?
    mov    eax, 4
    mov    ebx, 1
    mov    ecx, numbers
    add    ecx, edx
    mov    edx, 1
    int    0x80
    pop     ecx
    loop print

    ; linebreak
    mov    eax, 4
    mov    ebx, 1
    mov    ecx, linebreak
    mov    edx, 1
    int     0x80

    popad
%endmacro

SECTION .data
fizz:
    db "fizz",10
buzz:
    db "buzz",10
fizzbuzz:
    db "fizzbuzz",10
numbers:
    db "0123456789",10
linebreak:
    db 10

SECTION .text
GLOBAL _start
_start:
    ; initialize loop
    mov    ecx, 1

    mainloop:
    ; check for modulo 3
    mov    ebx, 3
    mov    eax, ecx
    xor    edx, edx
    div    ebx
    cmp    edx, 0
    je    d31

    ; check for modulo 5 if not modulo 3
    mov    ebx, 5
    mov    eax, ecx
    xor    edx, edx
    div    ebx
    cmp    edx, 0
    je     buzzget
   
    ; print number if not modulo 3 or 5
    printnumber ecx
    jmp    loopcheck

    ; how do i long jump///////
    d31:
    jmp d3

    ; modulo 5 not 3 print buzz
    buzzget:
    push    ecx
    mov    eax, 4
    mov    ebx, 1
    mov    ecx, buzz
    mov    edx, 5
    int     0x80
    pop    ecx
    jmp    loopcheck

    ; check for modulo 5 if modulo 3
    d3:
    mov    ebx, 5
    mov    eax, ecx
    xor    edx, edx
    div    ebx
    cmp    edx, 0
    je    fizzbuzzget

    ; modulo 3 not 5 print fizz
    fizzget:
    push    ecx
    mov    eax, 4
    mov    ebx, 1
    mov    ecx, fizz
    mov    edx, 5
    int     0x80
    pop    ecx
    jmp    loopcheck

    ; modulo 3 and 5 print fizzbuzz
    fizzbuzzget:
    push    ecx
    mov    eax, 4
    mov    ebx, 1
    mov    ecx, fizzbuzz
    mov    edx, 9
    int     0x80
    pop    ecx

    ; loop check
    loopcheck:
    inc    ecx
    cmp    ecx, 101
    jne     mainloop

    ; terminate
    mov    eax, 1
    xor    ebx, ebx
    int    0x80


More cycles can certainly be squeezed out of this.
Is there any better way to print numbers than my horrid Θ(log10n) macro?

Name: Anonymous 2009-05-24 2:03

>>16
You changed the register short to simply int? Why would you do that?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List