Created
May 17, 2014 11:25
-
-
Save MihailJP/2c78a62157cdade82f7c to your computer and use it in GitHub Desktop.
GCD and LCM of two numbers, implemented with Forth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
\ 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