Page 1 of 1

Simple GCD

Posted: Mon Mar 30, 2009 7:59 pm
by michaeled314

Code: Select all

Procedure.l gcd(a,b)
 While b <> 0
  t = b
  b = a % b
  a = t
 Wend
 ProcedureReturn a
EndProcedure
by the Euclidean Algorithm

Posted: Mon Mar 30, 2009 10:15 pm
by akj
Here is a slightly shorter procedure:

Code: Select all

Procedure gcd(a,b)
While b
  a % b
  Swap a, b
Wend
ProcedureReturn a
EndProcedure

Posted: Fri Apr 10, 2009 6:40 pm
by michaeled314
is this possible for ASM

Posted: Fri Apr 10, 2009 6:43 pm
by DarkDragon
It is possible in assembler, as purebasic compiles to assemblercode and then the assembler assembles the assemblercode to machinecode.

Just look at the /COMMENTED argument of the purebasic compiler.

It will give you this:

Code: Select all

; :
; Procedure.l gcd(a,b)
macro MP0{
_Procedure0:
  PUSH   ebx
  PS0=12
  XOR    eax,eax
  PUSH   eax                                                                                                                                                                                                                  
; While b <> 0
_While1:
  MOV    ebx,dword [esp+PS0+4]
  AND    ebx,ebx
  JE    _Wend1
; t = b
  MOV    eax,dword [esp+PS0+4]
  MOV    dword [esp],eax
; b = a % b
  MOV    ebx,dword [esp+PS0+0]
  MOV    eax,ebx
  CDQ
  IDIV   dword [esp+PS0+4]
  MOV    ebx,edx
  MOV    dword [esp+PS0+4],ebx
; a = t
  MOV    eax,dword [esp]
  MOV    dword [esp+PS0+0],eax
; Wend
  JMP   _While1
_Wend1:
; ProcedureReturn a
  MOV    eax,dword [esp+PS0+0]
  JMP   _EndProcedure1
; EndProcedure
  XOR    eax,eax
_EndProcedure1:
  ADD    esp,4
  POP    ebx
  RET    8
}
Now start optimizing it and put ! in front of it. But don't mess it up with the surroundings.