# X86 Largest Common Factor

For this program you will find the largest common factor for 2 numbers, a and b.

The largest common factor is the largest positive number that divides the two numbers.

The C++ code for doing this is:

int LCF (int a, int b)

{

if (a == 0 && b == 0)

b = 1;

else

if (b == 0)

b = a;

else

if (a != 0)

while (a != b)

if (a < b)

b -= a;

else

a -= b;

return b;

}

In your code, you should follow this C++ code as closely as possible.

Put a in eax, and b in ebx.

Do not use any loop instructions directly.

Do use compare and jump instructions.

Do not use any procedures except MyProgram.

Example of your console window should look as follows:

Please provide an integer for b: 8

Please provide an integer for a: 4

The largest common factor of a and b is: +4

Solution

INCLUDE NoIrvineBegin.inc

.data

prompta DB  “Please provide an integer for a: “,0

promptb DB  “Please provide an integer for b: “,0

result  DB  “The largest common factor of a and b is: “,0

numa  DD    0

numb  DD    0

.code

MyProgram PROC

mov edx,OFFSET prompta  ; prompt user to give a number for a

call  WriteString

call  ReadInt                 ; read an integer into eax

mov         numa,eax          ; save read number in a

mov edx,OFFSET promptb  ; prompt user to give a number for b

call  WriteString

call  ReadInt                 ; read an integer into eax

mov         numb,eax          ; save read number in b

mov eax,numa                  ; Puts a in eax,

mov   ebx,numb                ; puts b in ebx.

cmp eax,0                     ; if (a == 0

jne else1

cmp ebx,0                     ;           && b == 0)

jne else1

mov ebx,1                     ;     b = 1;

jmp return

else1:                                    ; else

cmp ebx,0                     ;     if (b == 0)

jne else2

mov ebx,eax                   ;     b = a;

jmp return

else2:                                    ; else

cmp eax,0                     ;           if (a != 0)

je  return

while1:                                   ;                      while (a != b)

cmp eax,ebx

je    return

cmp eax,ebx                   ;                       if (a < b)

jge else3

sub ebx,eax                   ;                             b -= a;

jmp while1

else3:                                    ;                 else

sub eax,ebx                   ;                             a -= b;

jmp while1

return:                                   ; here, b (ebx) has the largest common factor

mov  edx,OFFSET result  ; print result message

call WriteString

mov   eax,ebx                ; move ebx to eax for printing

call WriteInt                 ; print b, the largest common factor

call CrLf                     ; print a newline

ret

MyProgram ENDP

INCLUDE NoIrvineEnd.inc

END MyProgram