## Monday, November 24, 2014

On this post we're going to take the program from the previous post and change it so that it takes 4 sets of numbers and finds the gcd between them one by one.

Her'es the program:

.586
.model flat, c
.stack 100h
.data

;gcd(3241343, 948324), gcd(31243,68455),gcd(75324,729345),gcd(327256,647384)
left dword 3241343, 31243, 75324, 327256
right dword 948324, 68455, 729345, 647384

.code

doit proc
xor ecx,ecx
doagain:
push left[ecx]
push right[ecx]
call gcd
cmp ecx,16
jle doagain
ret

doit endp

gcd proc
mov eax,[esp + 8]      ; move the larger number of the first division problem into eax
repeatHere:
again:
xor edx,edx             ; zeroing out edx to prevent Integer overflow
mov ebx,[esp + 4]       ; hijacking ecx to represent right in the division problem
div ebx                 ; performing the first division problem of the loop
mov eax,[esp + 4]
mov [esp + 4],edx       ; preparing the numbers for the next time around
xor edx,edx             ; hijacking edx to represent the 0 in the compare
cmp [esp + 4], edx      ; comparing right to zero because we stop at when the second number becomes zero
jne again               ; if right isn't zero we jump back to the beginning

ret

gcd endp

end

As you can see it's almost the same as the previous program but with a few small changes,well actually big changes,such as the fact that I now have 2 procedures instead of 1 and that's because a procedure is supposed to do one thing and do it well,also left and right don't appear to be here,but they are. They've been pushed onto the stack which is why we use the stack pointer to represent them. You might think: "Why not just access the stack pointer,and the stack pointer plus 4?" Well we have to skip past the return address of the call to gcd. Also when we get back around to the point where we push left and right onto the stack we take them off the stack by adding 8 to the stack pointer which lowers the stack pointer down to the return address of that call so that we don't have to lower it past all those numbers at the very end kinda like this....

And the reason it's like that is because gcd isn't supposed to do everything at once,it's supposed to do one thing and do each part of it one at a time,kinda like this dentist cartoon,if you wait to floss for the entire year all the plaque builds up and then it's hard to get it all out,but if you do it consistently every day there will be a lot less plaque so it will be a lot easier.

WELL TTFN TA TA FOR NOW!!!!!!!!!!!!!!!!!!!!