Algorithms in Assembly Programming
Algorithms in Assembly Programming
● while (b ≠ 0) {
● temp = b;
● b = a % b;
● a = temp;
● }
● return a;
🧾 Assembly (NASM-like):
None
● section .text
● global main
● main:
● mov eax, 48 ; a = 48
● mov ebx, 18 ; b = 18
●
● gcd_loop:
● cmp ebx, 0
● je done
● xor edx, edx ; clear edx before division
● div ebx ; eax / ebx → quotient in eax, remainder
in edx
● mov eax, ebx
● mov ebx, edx
● jmp gcd_loop
●
● done:
● ; GCD is now in EAX
● int fact = 1;
● for (int i = n; i > 1; i--) {
● fact *= i;
● }
🧾 Assembly:
None
● section .text
● global main
● main:
● mov ecx, 5 ; n = 5
● mov eax, 1 ; result = 1
●
● fact_loop:
● mul ecx ; eax *= ecx
● loop fact_loop ; ecx-- and jump if ecx ≠ 0
●
● ; Result in EAX
● sum = n * (n + 1) / 2
🧾 Assembly:
None
● section .text
● global main
● main:
● mov eax, 10 ; n = 10
● mov ebx, eax ; copy n to ebx
● inc eax ; eax = n + 1
● mul ebx ; eax *= ebx (eax = n * (n + 1))
● shr eax, 1 ; divide by 2 using shift right (eax =
eax / 2)
●
● ; Result in EAX
✅ 4. Prime Checker
📖 Logic:
C/C++
● Keep track of which registers are volatile (e.g., EAX, ECX, EDX are often changed during
function calls).
● Use comments generously for clarity.
📘 Practice Ideas
Try implementing these in x86 Assembly:
●