Skip to content

Instantly share code, notes, and snippets.

@MihailJP
Created May 17, 2014 11:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MihailJP/2c78a62157cdade82f7c to your computer and use it in GitHub Desktop.
Save MihailJP/2c78a62157cdade82f7c to your computer and use it in GitHub Desktop.
GCD and LCM of two numbers, implemented with Forth
\ This implements Euclidean algorithm in Forth
: gcd ( X Y )
2dup <= if swap ( Y X ) then
( X Y )
begin
tuck ( Y X Y )
mod ( Y Z )
dup ( Y Z Z )
0= until ( Y Z )
( Y 0 )
drop ( Y )
;
\ Calculates LCM of two integers
: lcm ( X Y )
2dup ( X Y X Y )
* ( X Y P )
rot rot ( P X Y )
gcd ( P Q )
/ ( LCM )
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment