Created
March 15, 2015 18:28
-
-
Save giuscri/c1594357f6c2c4aedad6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; This one seems to be hot stuff: find all the prime | |
;; numbers under a certain limit (e.g. 2048). | |
%include "asm_io.inc" | |
section .data | |
guess dd 0 | |
factor dd 0 | |
limit dd 0 | |
prompt db "Find primes up to: ", 0 | |
section .text | |
global asm_main | |
asm_main: | |
enter 0, 0 | |
pusha | |
;; Ask user to type the limit ... | |
mov eax, prompt | |
call print_string | |
call read_int | |
mov [limit], eax | |
;; Print out the first two primes ... | |
mov eax, 2 | |
call print_int | |
call print_nl | |
mov eax, 3 | |
call print_int | |
call print_nl | |
;; Setup the first guess ... | |
mov eax, 5 | |
mov [guess], eax | |
primesloop: | |
;; If guess > limit, jump to the end of the primes loop ... | |
mov eax, [guess] | |
mov ebx, [limit] | |
cmp eax, ebx | |
ja endprimesloop | |
;; Else, setup factor to 3 ... | |
mov eax, 3 | |
mov [factor], eax | |
factorsloop: | |
;; If factor**2 >= guess, jump to the end of the factors loop ... | |
mov eax, [factor] | |
mul eax | |
mov ebx, [guess] | |
cmp eax, ebx | |
jae endfactorsloop | |
;; If guess % factor is zero, jump to the end of the factors loop ... | |
mov edx, 0 | |
mov eax, [guess] | |
mov ebx, [factor] | |
div ebx | |
mov ebx, edx | |
mov eax, 0 | |
cmp eax, ebx | |
je endfactorsloop | |
;; Else, increment factor by 2 and jump to the start of the factors loop ... | |
mov eax, [factor] | |
mov ebx, 2 | |
add eax, ebx | |
mov [factor], eax | |
jmp factorsloop | |
endfactorsloop: | |
;; If guess % factor is zero, continue ... | |
mov eax, [guess] | |
mov ebx, [factor] | |
mov edx, 0 | |
div ebx | |
mov ebx, edx | |
mov eax, 0 | |
cmp eax, ebx | |
je continueprimesloop | |
;; Else, you've found a prime: print it out! | |
mov eax, [guess] | |
call print_int | |
call print_nl | |
continueprimesloop: | |
;; Then, increment the guess by two and jump to the start of the primes loop ... | |
mov eax, [guess] | |
mov ebx, 2 | |
add eax, ebx | |
mov [guess], eax | |
jmp primesloop | |
endprimesloop: | |
popa | |
mov eax, 0 | |
leave | |
ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment