Simple GCD

Share your advanced PureBasic knowledge/code with the community.
michaeled314
Enthusiast
Enthusiast
Posts: 340
Joined: Tue Apr 24, 2007 11:14 pm

Simple GCD

Post 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
akj
Enthusiast
Enthusiast
Posts: 668
Joined: Mon Jun 09, 2003 10:08 pm
Location: Nottingham

Post 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
Anthony Jordan
michaeled314
Enthusiast
Enthusiast
Posts: 340
Joined: Tue Apr 24, 2007 11:14 pm

Post by michaeled314 »

is this possible for ASM
DarkDragon
Addict
Addict
Posts: 2345
Joined: Mon Jun 02, 2003 9:16 am
Location: Germany
Contact:

Post 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.
bye,
Daniel
Post Reply