Monday 25 February 2019

Assembly: Calculating factorials using iteration



program factorial_iterative;
#include( "stdlib.hhf" )

// Phil Gardner

procedure factorial; @noframe; @nodisplay;
begin factorial;

    cmp( ax, 0 );

    // Can't deal with factorial of negative number
    jl tooSmall;

    // Zero or above can be displayed though

    // Factorial of 0 is automatically 1
    jz isZero;

    // Any number larger than 1 requires working out
    stdout.put( nl, "Calculating factorial of " )
    stdout.puti16( ax );
    stdout.put( " is " );
    stdout.puti16( ax );

    mov( ax, bx );

    keepMultiplying:

       dec( bx );

       cmp( bx, 0 );

       jz finishedFactorial;

       mul( bx, ax );

       stdout.put( " x " );
       stdout.puti16( bx );

    jmp keepMultiplying;

    isZero:

       stdout.put( nl, "Factorial of 0 is always 1" );
       mov( 1, ax );


    finishedFactorial:

       stdout.put( nl, "Returning result ")
       stdout.puti16( ax );
       stdout.put( nl );

       ret();

    tooSmall:

       stdout.put( nl, "Must be >= 0", nl );
       ret();

end factorial;


// - - - - -

begin factorial_iterative;


    mov( -1, cx );

    keepCalculatingRange:

       mov( cx, ax );

       call factorial;
       inc( cx );
       cmp( cx, 6 );
    jle keepCalculatingRange;

    stdout.put( nl, "Finished.", nl );

end factorial_iterative;