Advertisement
STANAANDREY

gcd of 2 digits

Nov 5th, 2024
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. section .data
  2.     result_msg db "GCD is: ", 0
  3.     result_len equ $ - result_msg
  4.     newline db 0xA
  5.  
  6. section .bss
  7.     num1 resb 2       ; 1 digit + newline
  8.     num2 resb 2
  9.    
  10. section .text
  11.     global _start
  12.  
  13. _start:
  14.  
  15.     ; Read first digit
  16.     mov rax, 0
  17.     mov rdi, 0
  18.     mov rsi, num1
  19.     mov rdx, 2        ; 1 digit + newline
  20.     syscall
  21.  
  22.     ; Read second digit
  23.     mov rax, 0
  24.     mov rdi, 0
  25.     mov rsi, num2
  26.     mov rdx, 2
  27.     syscall
  28.  
  29.     ; Convert ASCII to numbers
  30.     movzx rax, byte [num1]   ; First number
  31.     sub rax, '0'             ; Convert from ASCII
  32.    
  33.     movzx rbx, byte [num2]   ; Second number
  34.     sub rbx, '0'             ; Convert from ASCII
  35.  
  36.     ; Calculate GCD using repeated subtractions
  37. gcd_loop:
  38.     cmp rax, rbx        ; Compare numbers
  39.     je gcd_done         ; If equal, we found GCD
  40.     jl smaller          ; If RAX < RBX, swap
  41.     sub rax, rbx        ; Subtract smaller from larger
  42.     jmp gcd_loop
  43.    
  44. smaller:
  45.     sub rbx, rax        ; RBX is larger, subtract RAX from it
  46.     jmp gcd_loop
  47.  
  48. gcd_done:
  49.     ; Print result message
  50.     push rax            ; Save result
  51.     mov rax, 1
  52.     mov rdi, 1
  53.     mov rsi, result_msg
  54.     mov rdx, result_len
  55.     syscall
  56.     pop rax             ; Restore result
  57.  
  58.     ; Convert result to ASCII
  59.     add rax, '0'        ; Convert to ASCII
  60.  
  61.     ; Print result digit
  62.     push rax
  63.     mov rax, 1
  64.     mov rdi, 1
  65.     mov rsi, rsp        ; Print from stack
  66.     mov rdx, 1
  67.     syscall
  68.     pop rax
  69.  
  70.     ; Print newline
  71.     mov rax, 1
  72.     mov rdi, 1
  73.     mov rsi, newline
  74.     mov rdx, 1
  75.     syscall
  76.  
  77.     ; Exit
  78.     mov rax, 60
  79.     mov rdi, 0
  80.     syscall
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement