【发布时间】:2021-11-04 22:16:41
【问题描述】:
我正在尝试编写一个程序来查找第 n 个素数 - 在本例中为第 10001 个素数。
目前,程序将每个数字都检测为质数,所以我的结果最终是 10002。
在 GDB 中单步执行程序时,从要除的素数数组中检索的值不是预期的 - 即在确定 3 是素数之后,下一次迭代 4,程序从数组中检索 770。
代码是:
%include '../resources.asm'
SECTION .data
SECTION .text
global main
extern malloc, free, calloc
main:
; Allocate space for primes
mov rsi, 8
mov rdi, 10001
call calloc
; Store address in r10
mov r10, rax
; First prime is 2
mov qword [r10], 2
; r11 is current number of primes found
mov r11, 1
; r12 is current number being checked
mov r12, 2
.outer:
; Move to next number
inc r12
; Reset array index
mov rcx, 0
.inner:
; Get number and divisor in rax and rbx respectively
mov rax, r12
mov qword rbx, [r10 + rcx] ;;;; Issue here, rbx is 770?
; Increment array index
inc rcx
; Get modulus
call umod
; If modulus is 0, number is not prime, move to next number
cmp rax, 0
jz .outer
; See if we've hit the end of current list of primes
cmp rcx, r11
jnz .inner
; If we are at the end of the list of primes, move the current number into the array
mov qword [r10 + rcx], r12
inc r11
; Stop if we've got the 10001st prime
cmp r11, 10001
jl .outer
还有来自资源的 umod sn-p
;
; int udiv(int rax, int rbx) -> rax, rbx
; Unsigned division
udiv:
push rdx
xor rdx, rdx
div rbx
mov rbx, rdx
pop rdx
ret
;
; int umod(int rax, int rbx) -> rax
; Unsigned modulus operation
umod:
call udiv
mov rax, rbx
ret
注意,我意识到我可能没有遵循参数传递等的正确约定。如果您认为对您有帮助,请随时做笔记。
【问题讨论】:
-
在存储 8 字节实体时,您需要将索引缩放到主缓冲区中。
-
@500-InternalServerError 谢谢。我不知道为什么我没有考虑扩展我的索引!