assemblyrecursionmoduluslow-levelhla

Recursive Division Assembly program


I am working on an assembly, techincally HLA (High Level Assembly), program. I need to convert this C code to assemvbly. Here is the assignment. Write an HLA Assembly language program that implements the following function:

procedure recursiveModulo( a: int32; b : int32 ); @nodisplay; @noframe;

This function should return into EAX the value of a % b based on a recursive approach. For simplicity sake, let's assume that both a and b will be greater than or equal to zero. By using recursion, you will be forced to manipulate the runtime stack. Base your solution on the following formulas:

Here is the provided C code:

int recursiveModulo( int a, int b ) 
{
   int result = 0;
   if (a == 0 || b == 0)
   {
     result = 0;
   }
   else if (b == 1)
   {
     result = 0;
   }
   else if (a < b)
   {
    result = a;
   } 
   else
   {
     result = recursiveModulo( a-b, b );
   }
     return( result );
}

Here is my HLA code:

program RecursiveDivision;
#include( "stdlib.hhf" );
static
iDataValue1 : int32 := 0;
iDataValue2 : int32 := 0;

procedure recursiveModulo( a: int32; b : int32 ); @nodisplay; @noframe;
static
returnAddress : dword;


begin recursiveModulo;

pop(returnAddress);
pop(a);
pop(b);
push(returnAddress);
push(ECX);
push(EBX);


cmp(a, 0);
je equal;
jmp checkb;

checkb:
cmp(b, 0);
je equal;
jmp b1;

b1:
cmp(b, 1);
je equal;
jmp alessb;

equal:
mov(0, EAX);
jmp ExitSequence;

alessb:
mov(a, EBX);
cmp(b, EBX);
jg resulta;
jmp recursive;

resulta:
mov(a, EAX);
jmp ExitSequence;

recursive:
mov(a, ECX);
sub(b, ECX);
push(ECX);
push(b);
call recursiveModulo;
jmp ExitSequence;

ExitSequence:
pop(ECX);
pop(EBX);
ret();




end recursiveModulo;

begin RecursiveDivision;

stdout.put("Give me A",nl);
stdin.get(iDataValue1);
stdout.put("Give me B",nl);
stdin.get(iDataValue2);
push(iDataValue1);
push(iDataValue2);
call recursiveModulo;
stdout.puti32(EAX);


end RecursiveDivision;

So the part of my code that works correctly is the first if block. For the second if block where result should be zero if b = 1, is that it just simply returns 1 instead of 0. For the 3rd conditional where if a is less than b I get this weird issues where it works for some combinations of numbers, but other time it just returns zero. for the else block where it is supposed to call the function recursively it just simply returns parameter a. `


Solution

  • POP pops the last pushed value. You push first a then b, so you have to pop first b then a.

    Change

    pop(a);
    pop(b);
    

    to

    pop(b);
    pop(a);