汇编程序查找整数的所有除数

时间:2018-11-28 00:03:42

标签: assembly nasm

我正在尝试编写一个程序,该程序读取一个整数并找到该整数的所有除数(最多但不包括该整数)。找到除数后,将其推入堆栈,最后除数应按相反顺序打印。

这是我目前拥有的代码:

; global and external declarations

global _main
extern  read_int, print_int, print_string
extern  read_char, print_char, print_nl

segment .data
prompt01 db 10, "Enter an integer: ",0
out01 db "Divisors: ",0

segment .bss
a resd 1

segment .text

_main:

enter   0,0 ; setup routine
pusha

; prompt for number
mov eax, prompt01   ; prompt for a
call print_string

call read_int       ; input a
mov [a], eax        ; move from eax to a
xor ecx, ecx        ; zero out ecx register


; do the division
mov ebx, 1      ; divisor in ebx
L1: mov eax, [a]        ; dividend in eax
cdq         ; sign extend eax to edx:eax pair
div ebx         ; divide - quotient in eax, remainder in edx
; if edx is 0, push on stack
cmp edx, 0
je L2
jmp L3
 ; if remainder was zero, push on to stack
L2: push edx
inc ecx         ; increment counter loop
L3: inc ebx         ; increment divisor
cmp ebx, eax        ; check if ebx = eax
je out
jmp L1

; print out everything in the stack
out:    mov eax, out01
call print_string

jcxz done
L4: pop edx
call print_int
call print_nl
loop L4

done:   popa        ; return routine
mov eax, 0
leave
ret

预期输出类似于以下内容:

Enter an integer: 210
Divisors:
105
70
42
35
30
21
15
14
10
7
6
5
3
2
1

但是我实际上得到了:

Enter an integer: 210
Divisors: 4210712
4210712
4210712
4210712
4210712
4210712
4210712
4210712

由于Intel 80x86具有除法运算,所以我使用DIV除以我的数字,并使用CDQ命令对edx:eax对扩展eax进行签名。

我认为问题是在除法期间发生的,因为某些东西被压入堆栈(即使这不是正确的东西)。有什么想法可能会出错吗?

0 个答案:

没有答案
相关问题