简体   繁体   中英

Assembly language program to separate even and prime numbers using subroutines

I wish to generate an assembly language program to separate even and prime numbers from a given list of numbers. The program should make use of subroutines, stack and indirect addressing mode.

What I have tried is

.model small
  .data
     num db 0,13,4,7,8,9,14,15,2,10,19,20
     even dw 20 dup ?
     prime dw 20 dup ?

 .code
   mov ax, @ data
   mov ds, ax
   LEA BX,num
   LEA SI, even
   LEA DI, prime
   mov dh,02
L1:
   mov ah,00
   mov al, [BX]
   mov dl, al
   div dh
    cmp ah,00
    JE EVEN
EVEN:
     mov [SI], dl
     INC SI
     INC BX
     LOOP L1

As I am a beginner to assembly language, I wish to know the correct code for the above requirement. Any help would be appreciated.

The program should make use of subroutines

What your program must then do is run over the num array and call upon 2 subroutines, one that finds out if the number is prime and one that finds out if the number is even.
Currently you almost got a good loop, were it not that you forgot to initialize the CX register that the LOOP instruction depends on!

This is already a good loop:

    lea     bx, num
    lea     si, even
    lea     di, prime
    mov     cx, 12         ; There are 12 numbers in the 'num' array
L1:
    mov     al, [bx]
    call    TestForEven
    call    TestForPrime
    inc     bx
    loop    L1

Your test to find out if a number is even uses a division by 2. This is a wasteful solution. All you got to do is check if the lowest bit of the number is 0.

TestForEven:
    test    al, 1         ; This tests the lowest bit
    jnz     NotEven
    mov     [si], al      ; Adding to the 'even' array
    inc     si
NotEven:
    ret

Here are some tips to complete the task:

  • Like @Michael wrote in his comment, you should have the even and prime arrays defined as bytes.
  • If any number is found to be even, it can't be prime also. This means that you could make the call to TestForPrime from within TestForEven (instead of from the main loop).

     TestForEven: test al, 1; This tests the lowest bit jnz NotEven mov [si], al; Adding to the 'even' array inc si ret NotEven: call TestForPrime ret

    And because this embedded call has now become what is called a tail-call, the call instruction is no longer needed:

     TestForEven: test al, 1; This tests the lowest bit jnz TestForPrime mov [si], al; Adding to the 'even' array inc si ret TestForPrime: ... ret
  • If you search this forum (or google) you will certainly find good ways to test for a prime number. Good hunting...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM