forked from algorithm-archivists/algorithm-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheuclidean_example.s
75 lines (70 loc) · 1.8 KB
/
euclidean_example.s
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
.intel_syntax noprefix
.section .rodata
euclid_mod_fmt: .string "[#]\nModulus-based euclidean algorithm result:\n%d\n"
euclid_sub_fmt: .string "[#]\nSubtraction-based euclidean algorithm result:\n%d\n"
.section .text
.global main
.extern printf
# rdi - a
# rsi - b
# RET rax - gcd of a and b
euclid_mod:
mov rax, rdi # Get abs of a
sar rax, 31
xor rdi, rax
sub rdi, rax
mov rax, rsi # Get abs of b
sar rax, 31
xor rsi, rax
sub rsi, rax
jmp mod_check
mod_loop:
xor rdx, rdx # Take the mod of a and b
mov rax, rdi
div rsi
mov rdi, rsi # Set b to the mod of a and b
mov rsi, rdx # Set a to b
mod_check:
cmp rsi, 0 # Check if b is non-zero
jne mod_loop
mov rax, rdi # Return the result
ret
euclid_sub:
mov rax, rdi # Get abs of a
sar rax, 31
xor rdi, rax
sub rdi, rax
mov rax, rsi # Get abs of b
sar rax, 31
xor rsi, rax
sub rsi, rax
jmp check
loop:
cmp rdi, rsi # Find which is bigger
jle if_true
sub rdi, rsi # If a is bigger then a -= b
jmp check
if_true:
sub rsi, rdi # Else b -= a
check:
cmp rsi, rdi # Check if a and b are not equal
jne loop
mov rax, rdi # Return results
ret
main:
mov rdi, 4288 # Call euclid_mod
mov rsi, 5184
call euclid_mod
mov rdi, OFFSET euclid_mod_fmt # Print output
mov rsi, rax
xor rax, rax
call printf
mov rdi, 1536 # Call euclid_sub
mov rsi, 9856
call euclid_sub
mov rdi, OFFSET euclid_sub_fmt # Print output
mov rsi, rax
xor rax, rax
call printf
xor rax, rax # Return 0
ret