-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsum_sq_diff.asm
More file actions
88 lines (59 loc) · 1.32 KB
/
sum_sq_diff.asm
File metadata and controls
88 lines (59 loc) · 1.32 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
global _start
extern printf
section .text
_start:
; eax
mov rdi, 100
call sum_consec_squares
mov rbx, rax
push rbx
call sum_consec_int
pop rbx
imul rax, rax
sub rax, rbx
mov rdi, rax
call print_result
call _end_execution
; We use a nice little formula which can be easily derived;
; -> (n * (n + 1)(2n + 1))/6
sum_consec_squares:
mov rcx, 6
mov rax, rdi
inc rax
; ebx = (2n + 1)
mov rbx, rdi
imul rbx, 2
inc rbx
imul rax, rbx
imul rax, rdi
; rax is now the numerator
xor rdx, rdx
idiv rcx
ret
; Sum consecutive integers is n(n + 1) / 2
sum_consec_int:
mov rbx, 2
mov rax, rdi
inc rax
imul rax, rdi
xor rdx, rdx
idiv rbx
ret
print_result:
mov ebx, edi
push rdi
mov rdi, format
mov esi, ebx
xor rax, rax
call printf
pop rdi
ret
_end_execution:
mov rax, 60
mov rdi, 0
syscall
ret
section .data
format:
db "%ld", 10, 0
; vim: ft=nasm