Assembly Language MASM32 Greatest Common Divisor Objective T

Assembly Language (MASM32): Greatest Common Divisor

Objective: To be accustomed to integer multiplication and division.

The greatest common divisor (GCD) of two integers is the largest integer that will evenly divide both integers. The GCD algorithm involves integer division in a loop, described by the following pseudocode:

int GCD (int x, int y)
{
X = abs(X)
Y = abs(Y)
do {
int n = X mod Y
x = y
y = n
} while ( y != 0 )
return X
}

The least (or lowest) common multiple (LCM) of two integers is the smallest number that is multiple of both numbers. If GCD (x, y) is known, then LCM (x, y) can be found as:

x*y/GCD(x, y)

Implement these functions as assembly language procedures with the parameters of SDWORD or SWORD types and write a test program that calls the pair of functions several times, passing it different values.

The good idea is to do the interactive input. Make sure your program handles zero values for X or Y.

The sample output is shown below.

-----------------

First Number: 18

Second Number: 12

The Greatest Common Divisor is 6

The Lowest Common Multiple is 36

Continue? (Y/N)

Y

First Number: -15

Second Number: 45

The Greatest Common Divisor is 15

The Lowest Common Multiple is 45

Continue? (Y/N)

N

Solution

Answer:

MIPS Assembly Language Code:

GCD(int, int):
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-20], edi
mov DWORD PTR [rbp-24], esi
mov eax, DWORD PTR [rbp-20]
sar eax, 31
xor DWORD PTR [rbp-20], eax
sub DWORD PTR [rbp-20], eax
mov eax, DWORD PTR [rbp-24]
sar eax, 31
xor DWORD PTR [rbp-24], eax
sub DWORD PTR [rbp-24], eax
.L5:
mov eax, DWORD PTR [rbp-20]
cdq
idiv DWORD PTR [rbp-24]
mov DWORD PTR [rbp-4], edx
mov eax, DWORD PTR [rbp-24]
mov DWORD PTR [rbp-20], eax
mov eax, DWORD PTR [rbp-4]
mov DWORD PTR [rbp-24], eax
cmp DWORD PTR [rbp-24], 0
je .L4
jmp .L5
.L4:
mov eax, DWORD PTR [rbp-20]
pop rbp
ret
__static_initialization_and_destruction_0(int, int):
push rbp
mov rbp, rsp
sub rsp, 16
mov DWORD PTR [rbp-4], edi
mov DWORD PTR [rbp-8], esi
cmp DWORD PTR [rbp-4], 1
jne .L9
cmp DWORD PTR [rbp-8], 65535
jne .L9
mov edi, OFFSET FLAT:std::__ioinit
call std::ios_base::Init::Init()
mov edx, OFFSET FLAT:__dso_handle
mov esi, OFFSET FLAT:std::__ioinit
mov edi, OFFSET FLAT:std::ios_base::Init::~Init()
call __cxa_atexit
.L9:
nop
leave
ret
push rbp
mov rbp, rsp
mov esi, 65535
mov edi, 1
call __static_initialization_and_destruction_0(int, int)
pop rbp
ret

Assembly Language (MASM32): Greatest Common Divisor Objective: To be accustomed to integer multiplication and division. The greatest common divisor (GCD) of two
Assembly Language (MASM32): Greatest Common Divisor Objective: To be accustomed to integer multiplication and division. The greatest common divisor (GCD) of two

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site