Search code examples
assemblymasm32

Calculate the sum of negative-only_and_divisible_by_4 integers


I have a question that I am studying for my final exam. This is the question:

Write the program to calculate the sum of negative-only_and_divisible_by_4 integers entered (from keyboard) by the user until the user enters positive value 100.

Below is my code and it is working. I am wondering though is there a more efficient way to check to see if the number is divisible by 4.

.data

prompt BYTE "No Positive Numbers!",0
done BYTE "Finished..",0
notdivisible BYTE "This number is not divisble!",0

.code
start:


mov ebx,0

readin:
    call ReadInt
    cmp eax,100
    je finish
    cmp eax,0
    jg positive
    mov ecx,eax
    neg ecx
checkifdivisible:   
    sub ecx,4
    cmp ecx,0
    jl notdiv
    jg checkifdivisible
    je divisible

divisible:
    add ebx,eax
    LOOP readin

notdiv:
    mov edx,OFFSET notdivisible
    call WriteString
    call Crlf
    jmp readin

positive:
    mov edx,OFFSET prompt
    call WriteString
    call Crlf
    jmp readin

finish:
    call Crlf
    mov edx,OFFSET done
    call WriteString

    xchg ebx,eax
call Crlf
call WriteInt


exit
end start

Thank you all in advance for helping me make more efficient code! I feel like this answer is too long.


Solution

  • A number n is dividable by 4 if n AND 3 == 0. C check:

    #include <stdio.h>
    #include <stdint.h>
    
    static void
    is_div4(int32_t n)
    {
      printf("%5d => 0x%08x, %d, %.2f\n",
        n, n, ((uint32_t) n & 3) == 0, (double) n / 4.0);
    }
    
    int
    main(int argc, char **argv)
    {
      is_div4(-100);
      is_div4(-4);
      is_div4(-102);
      is_div4(-338);
      is_div4(-108);
    
      return 0;
    }
    

    output:

     -100 => 0xffffff9c, 1, -25.00
       -4 => 0xfffffffc, 1, -1.00
     -102 => 0xffffff9a, 0, -25.50
     -338 => 0xfffffeae, 0, -84.50
     -108 => 0xffffff94, 1, -27.00
    

    Simple implementation:

        mov     eax, NUMBER
        and     eax, 0x3
        cmp     eax, 0
        jne     NotDividableBy4
        ; dividable by 4
    NotDividableBy4:
        ;