ASM 中的 isPrime 始终给出相同的输出

问题描述 投票:0回答:1

我一直在努力学习ASM,这是我一直在努力解决的问题之一。
该算法的目标是检查一个数字是否是素数。根据我的头脑,这应该可行。然而事实并非如此。无论输入如何,我都会得到相同的输出。如果这是用任何其他语言,我会在各处添加 PRINT 语句来调试,但我不能这样做。有谁能够提供有关为什么这可能行不通的见解吗?

section .data
    number db 15 ; 
    answer db 1 ; 1 -> prime, 0 -> not prime
    prime_msg db 'Number is prime', 0x0a
    not_prime_msg db 'Number is NOT prime', 0x0a
    
    section .bss
    divisor resb 1 ; Reserve one byte for the divisor
    
    section .text
    global _start
    
    _start: 
        mov al, [number]
        mov bl, 2 ; divisor = 2
    
    while_loop:
        cmp bl, al
        jg end  ;if number (al) is < divisor(bl) jump to end
        
        mov dl, al ; Move number into DL
        mov al, bl ; Move divisor into AL
         
        xor ah, ah ;clear remainder
        div bl     ;div al by bl(divisor)
        
        cmp ah, 0  ;compare remainder to 0
        je not_prime ;jump to not_prime if 0
        
        inc bl 
        jmp while_loop
        
    not_prime:
        mov byte [answer], 0
        
    out_not:
        mov edx, 16 ; Length of prime_msg ('Number is prime\n')
        mov ecx, prime_msg ; Pointer to prime_msg
        mov ebx, 1 ; File descriptor for stdout
        mov eax, 4 ; sys_write system call
        int 0x80 ; Make the system call
    
        ; Exit the program
        mov eax, 1 ; sys_exit system call
        xor ebx, ebx ; Return code 0
        int 0x80 ; Make the system call
        
    out_prime:
        mov edx, 20 ; Length of not_prime_msg
        mov ecx, not_prime_msg ; Pointer to not_prime_msg
        mov ebx, 1 ; File descriptor for stdout
        mov eax, 4 ; sys_write system call
        int 0x80 ; Make the system call
    
        ; Exit the program
        mov eax, 1 ; sys_exit system call
        xor ebx, ebx ; Return code 0
        int 0x80 ; Make the system call
        
    end:
        cmp byte[answer], 0 
        je out_not ;if answer = 0 -> not prime
        
        jmp out_prime ;else prime

我尝试更改循环的条件,但没有帮助。我只是设法更改给出的输出,但无论输入如何,它仍然是相同的。

assembly x86 primes
1个回答
0
投票

无论输入如何,它仍然是相同的。

您错误地将 BL 除以 BL,总是导致商=1,余数=0。
移动DL中的号码:

    mov   dl, [number]
    mov   bl, 2           ; divisor = 2
while_loop:
    cmp   bl, dl
    jg    end
    
    movzx ax, dl          ; Move NUMBER into AX
    div   bl              ; Div AX by BL
    test  ah, ah          ; Compare remainder to 0
    jz    not_prime
    inc   bl 
    jmp   while_loop

有关测试素数的更多信息,请阅读我的这个其他答案。它还包含优化的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.