Skip to content

Instantly share code, notes, and snippets.

@MihailJP
Created May 17, 2014
Embed
What would you like to do?
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