素数 - 汇编语言x86

时间:2017-04-12 02:59:34

标签: assembly x86 intel primes

我正在尝试使用x86英特尔汇编语言(NASM)编写一个小程序,该程序能够接收一个数字(在程序文本文件中进行硬编码)并检查该数字是否为素数,除数为2,如果需要,使用while循环继续递增。根据数字是否为素数,将显示特定消息,如果数字不是素数,则值0将被写入存储位置'answer'。否则,初始值“1”将保持不变,从而表明该数字为素数。

我相信我已经正确地增加了除数'bl'的值,但是使用jl loopy使程序再次通过循环似乎失败了,因为它产生了不正确的结果,例如5是素数,10不是素数,但15是素数。

这是我的代码:

section .data
    primeMsg db "This is a prime number!", 0xa
    lenPrimeMsg equ $-primeMsg
    noPrimeMsg db "This is not a prime number.", 0xa
    lenNoPrimeMsg equ $-noPrimeMsg

number db 5
answer db 1         ;1 means number is prime, 0 means number is not prime
section .bss

section .text
    global start

start:  
    mov esi, number     ;get the offset of number into esi
   keith: mov eax, 0        ;clear the entire eax register
    mov al, [esi]       ;get the number from memory into al 
    mov dl, al      ;put it inside dl as well
    mov bl, 2       ;bl holds each divisor starting from 2
loopy: div bl           ;ax/bl with quot in al and rem in ah
   and ax, 1111111100000000b    ;isolate the rem in ah with a AND mask to     determine whether the remainder is 0

    jz not_prime        ;if jump zero, goto not_prime
    inc bl          ;increment bl operand by one
    cmp bl, dl      ;compare bl and dl when bl is substracted from dl for result to be used in conditional jump
    jl loopy        ;loop continues if divisor is less than number

; message if number is prime
    push dword lenPrimeMsg
    push dword primeMsg
    push dword 1

    mov eax, 0x4
    sub esp, 4
    int 0x80

    add esp, 16

    push dword 1

    mov eax, 0x1
    sub esp, 4
    int 0x80

not_prime:
    mov eax, answer     
    mov eax,0       ;store 0 in answer if number is not prime

 ; message if number is NOT prime
    push dword lenNoPrimeMsg
    push dword noPrimeMsg
    push dword 1

    mov eax, 0x4
    sub esp, 4
    int 0x80

    add esp, 16

    push dword 1

    mov eax, 0x1
    sub esp, 4
    int 0x80

0 个答案:

没有答案