Skip to content

Commit 9b4454e

Browse files
committed
Add basic euclidian algorithm subtraction in Piet
1 parent f8929ce commit 9b4454e

File tree

6 files changed

+97
-0
lines changed

6 files changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
function gcd(a, b)
2+
while a ≠ b
3+
if a > b
4+
a := a − b;
5+
else
6+
b := b − a;
7+
return a;
8+
9+
in(number) A
10+
in(number) BA
11+
12+
// Start of loop
13+
duplicate BBA
14+
push 3 3BBA
15+
push 2 23BBA
16+
roll ABB
17+
duplicate AABB
18+
push 4 4AABB
19+
push 1 14AABB
20+
roll ABBA
21+
subtract 0/x BA
22+
not 1/0 BA // 1 if a = b and 0 if a ≠ b
23+
not 0/1 BA // 1 if a ≠ b and 0 if a = b
24+
pointer BA
25+
26+
// Go down if a ≠ b
27+
duplicate BBA
28+
push 3 3BBA
29+
push 2 23BBA
30+
roll ABB
31+
duplicate AABB
32+
push 4 4AABB
33+
push 1 14AABB
34+
roll ABBA
35+
push 2 2ABBA
36+
push 1 12ABBA
37+
roll BABA
38+
greater 0/1 BA // A > B; 1 if true; 0 if false
39+
pointer BA // maybe a switch here instead?
40+
41+
// If A > B
42+
duplicate BBA
43+
push 3 3BBA
44+
push 1 13BBA
45+
roll BAB
46+
subtract AB // A = A - B
47+
push 2 2AB
48+
push 1 12AB
49+
roll BA
50+
// Go back to start of loop
51+
52+
// If B > A
53+
// b = b - a
54+
push 2 2BA
55+
push 1 12BA
56+
roll AB
57+
duplicate AAB
58+
push 3 3AAB
59+
push 1 13AAB
60+
roll ABA
61+
subtract BA // B = B - A
62+
// Go back to start of loop
63+
64+
// Go right if a = b (end of while loop)
65+
pop A
66+
out(number) -
67+
68+
---------------------------------------------------------------------------
69+
70+
function gcd(a, b)
71+
while b ≠ 0
72+
t := b;
73+
b := a mod b;
74+
a := t;
75+
return a;
76+
77+
in(number) A
78+
in(number) BA
79+
80+
// Start of loop
81+
duplicate BBA
82+
not 0/1 BA
83+
not 1/0 BA
84+
pointer BA
85+
86+
// Go down if b ≠ 0
87+
duplicate TBA
88+
push 3 3TBA
89+
push 1 13TBA
90+
roll BAT
91+
mod BA // b = a mod b; a = t
92+
// Go back to the start of the loop
93+
94+
// Go right if b = 0
95+
pop A
96+
out(number) -
97+
Binary file not shown.
Loading
Binary file not shown.

0 commit comments

Comments
 (0)