Assembly – Check Prime Number

email me

Tested in Windows 10, with NASM v2.14.02.

; ----------------------------------------------------------------------------------------
; INFORMATION
; MrNetTek
; Check Prime Number
; eddiejackson.net/blog
; 3/9/2020
; free for public use
; free to claim as your own
;
; DOWNLOAD
; https://www.nasm.us/pub/nasm/releasebuilds/2.14.02/win64/
;
; SAVE AS
; prime.asm
;
; COMPILE
; nasm -fwin64 prime.asm && gcc -o prime.exe prime.obj && prime
; ----------------------------------------------------------------------------------------

bits 64
default rel

EXTERN printf
EXTERN scanf

SECTION .data

    input: DQ 0
    PrimeIsTrue: DQ 1
    count: DQ 0

    UserText: DB "Enter a number: ", 0
    fmt: DB "%d", 0
    PrimeTrue: DB "%d is prime", 10, 0
    PrimeFalse: DB "%d is not prime", 10, 0

SECTION .text

GLOBAL main
main:
    PUSH RBP
    MOV RBP, RSP

    SUB RSP, 32
    MOV RCX, UserText
    CALL printf
    ADD RSP, 32

    SUB RSP, 32
    MOV RDX, input
    MOV RCX, fmt
    CALL scanf
    ADD RSP, 32

    MOV RCX, [input]
    MOV [count], RCX

PrimeCheck:
    DEC QWORD [count]
    CMP QWORD [count], 2
    JGE HasNotReachedOne
    JMP EndVerifyPrime

HasNotReachedOne:
    MOV RAX, [input]
    CDQ
    MOV RBX, [count]
    IDIV RBX
    CMP EDX, 0
    JE Divisible
    JMP NotDivisible

Divisible:
    MOV QWORD [PrimeIsTrue], 0

NotDivisible:
    JMP PrimeCheck

EndVerifyPrime:
    CMP QWORD [PrimeIsTrue], 1
    JE IsPrime
    JMP IsNotPrime

IsPrime:
    SUB RSP, 32
    MOV RDX, [input]
    MOV RCX, PrimeTrue
    CALL printf
    ADD RSP, 32
    JMP EndIf
 
IsNotPrime:
    SUB RSP, 32
    MOV RDX, [input]
    MOV RCX, PrimeFalse
    CALL printf
    ADD RSP, 32

EndIf:
    MOV RBP, RSP
    POP RBP
    RET

; references
; https://www.computerhope.com/jargon/a/al.htm
; https://www.csee.umbc.edu/portal/help/nasm/sample.shtml
; https://montcs.bloomu.edu/~bobmon/Code/Asm.and.C/hello-asms.html