Advertisement
Guest User

asm prime

a guest
Apr 28th, 2015
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ; prime.asm
  2. ; sample program to demonstrate procedures
  3. ; calulates and prints prime numbers from 1 to 20
  4.  
  5. include 'emu8086.inc'
  6.  
  7. org  100h; set location counter to 100h
  8.  
  9. jmp CodeStart
  10.  
  11. DataStart:
  12.    max dw 20
  13.    space db " ", 0
  14.  
  15. CodeStart:
  16.    mov bx, 2;set this value to the number you want to start at I used 2 because 1 is not a prime.
  17.    
  18.    LoopStart:
  19.            
  20.                    
  21.  
  22.  ;call procedure IsPrime to test whether the number is
  23.  ;prime or not
  24.        call IsPrime
  25.        cmp dx, 0
  26.  ;if dx is equal to 0 jump
  27.        je Equal
  28.          
  29.        mov ax, bx
  30.        call print_num
  31.        
  32.  ; print a space
  33.        mov si, offset space
  34.        call print_string
  35.        
  36.     Equal:  
  37.        add bx, 1
  38.        cmp bx, max
  39.  
  40.    jle LoopStart
  41.    
  42.    ret
  43.  
  44.    IsPrime PROC
  45.  ; uses a loop to determine if number in bx is prime
  46.  ; upon return if bx not prime dx will be 0, otherwise dx > 0
  47.  
  48.  ; we only have to test divisors from 2 to bx/2
  49.        
  50.  ; prepare to divide dx:ax / 2
  51.        mov ax, bx    
  52.        mov dx, 0
  53.        mov cx, 2  
  54.        div cx
  55.        
  56.  ; move result into si for loop
  57.        mov si, ax
  58.        
  59.  ; assume the value is prime
  60.        mov dx, 1
  61.        
  62.  ; start loop count at 2
  63.        mov cx, 2
  64.        
  65.     PrimeLoop:
  66.        
  67.           ; compare loop count(in cx) and max loop value (in si)
  68.            cmp cx, si
  69.            
  70.           ; jump out of loop if count(cx) > si
  71.            ja StopLabel
  72.        
  73.           ; divide test value (in bx) by loop count (in cx)
  74.            mov ax, bx
  75.            mov dx, 0           
  76.            div cx
  77.            
  78.           ; check remainder (in dx), if zero then we found a divisor
  79.           ; and the number cannot be prime
  80.            cmp dx, 0
  81.            
  82.           ; if dx = 0 then we found a divisor and can stop looking
  83.            je StopLabel
  84.            
  85.           ; increment count
  86.            add cx, 1
  87.  
  88.          
  89.  
  90.      jmp PrimeLoop
  91.        
  92.      StopLabel:
  93.        
  94.      ret
  95.    IsPrime ENDP
  96.    
  97. DEFINE_PRINT_STRING
  98. DEFINE_SCAN_NUM
  99. DEFINE_PRINT_NUM
  100. DEFINE_PRINT_NUM_UNS
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement