Advertisement
Guest User

primo

a guest
Jan 3rd, 2020
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ; 3.  A prime number is an integer that is divisible only by 1 and by itself.
  2. ;
  3. ;  3.0   Write a program that takes a number m as input, and prints back 1 to the
  4. ;        console if m is a prime number. Otherwise, it prints 0.
  5. ;
  6. ;           ANSWER:
  7. ;
  8. ;               Take m, and divide it by all previous numbers. When one of the
  9. ;               divisions returns no remainder, it is not a prime, else it is.
  10.  
  11. format PE console
  12.  
  13. include 'C:\fasm\INCLUDE\win32a.inc'
  14.  
  15. ; ===============================================
  16. section '.text' code readable executable
  17.  
  18. _main:
  19.     mov ebp, esp; for correct debugging
  20.     call    read_hex
  21.     ; eax = input()
  22.    
  23.     mov     ecx, eax                        ; use a counter
  24.     ; ecx = eax
  25.  
  26.     mov     ebx, eax                        ; original user input in ebx, because we are gonna use eax in division
  27.     ; ebx = eax
  28.  
  29. _do_division:
  30.     dec     ecx
  31.     ; ecx = ecx - 1
  32.  
  33.     mov     esi, ecx                        ; when we reach ecx=1, do not divide, but print 1
  34.     ; esi = ecx
  35.  
  36.     sub     esi, 1
  37.     ; esi = esi - 1
  38.     jz      _set_eax_1
  39.     ; if esi = 0 then return 1 (jump to set_eax_1)
  40.    
  41.     cmp     ecx, 0                          ; never divide by 0, so check if we have ecx = 0 here
  42.     jz      _set_eax_1
  43.     ; if ecx = 0 then return 1 (jump to set_eax_1)
  44.    
  45.     mov     edx, 0                          ; clear edx for division
  46.     ; edx = 0
  47.     mov     eax, ebx
  48.     ; eax = ebx
  49.  
  50.     div     ecx                             ; edx:eax / ecx, result is stored in edx:eax (remainder:quotient)
  51.     ; edx = eax  / ecx
  52.  
  53.     cmp     edx, 0                          ; set the flags
  54.     jnz     _do_division
  55.     ; if edx = 0 then jump to do_division
  56.  
  57.     jmp     _set_eax_0
  58.     ; return 0 (jump to set_eax_1)
  59.  
  60. _set_eax_1:
  61.     mov     eax, 1
  62.     jmp     _print
  63.    
  64. _set_eax_0:
  65.     mov     eax, 0
  66.     jmp     _print
  67.    
  68. _print:
  69.     call    print_eax
  70.  
  71.     ; Exit the process:
  72.     push    0
  73.     call    [ExitProcess]
  74.  
  75.         ret
  76.  
  77. include 'C:\fasm\INCLUDE\training.inc'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement