【发布时间】:2017-11-02 23:14:10
【问题描述】:
outerLoop:
skipCarry:
mov eax, 2
mov inCompare, eax ;Set our inCompare to 2
mov eax, outCompare
push ecx ;Save status of these registers before entering the innerLoop
push eax
mov ecx, innerLoopCount
isComposite:
mov eax, outCompare ;Value to be checked for composite
mov edx, 0 ;Make sure edx does not have a left over value
div inCompare ;Divide outCompare by inCompare to see if we get a remainder of 0 in edx
cmp edx, 0
jne skipPrint ;If the remainder is not 0, we have not proven that the number in question is composite, so do not print
;Print out a composite value if its been proven
mov eax, outCompare
call WriteDec
mov edx, OFFSET spaces
call WriteString ;Write spaces between the composites
mov ebx, writeCounter
inc ebx ;This will help to make sure we start a new line after writing 10 composites
mov writeCounter, ebx
cmp ebx, 10 ;If counter is at 10, we start a new line
jne exitInnerLoop ;exit the inner loop because we found that the number in question is composite
call CrLf
mov writeCounter, 0
jmp exitInnerLoop ;exit the inner loop because we found that the number in question is composite
skipPrint: ;Jumped to if the number in question was not confirmed to be composite
;This is to continue testing for composite of the number in question by incrementing the divisor
mov ebx, inCompare
inc ebx
mov eax, outCompare
cmp eax, ebx
je exitInnerLoop
mov inCompare, ebx
skipIncrement: ;Will be jumped to if there are no new divisors to be tested
loop isComposite ;Retest with new divisior if there is a possibility
exitInnerLoop:
pop eax ;restore outer loop status
pop ecx
inc eax ;Next number to check for being composite
mov outCompare, eax
loop outerLoop
我收到错误代码,指出跳转太长了 5 个字节,指的是外循环。我知道只使用 jmp 命令并自己跟踪计数器会更简单,但我的家庭作业要求使用循环来代替。有没有办法扩展循环的范围,或者有没有办法将循环中的内容缩小 5 个字节,而我没有看到?
循环应该检查一个数字是否是复合的,只是为了知道功能。
【问题讨论】:
-
关于缩短代码...就像您希望的任何时候一样,有很多麻烦,您应该将值保存在寄存器中而不是内存中,将打印代码作为整个子程序放入子程序等...我在 codereview 网站上做了类似的回答,你可以检查它的一些技巧和想法(并强迫你使用
loop是 evil):codereview.stackexchange.com/questions/148315/… -
@Ped7g:我花了太多时间优化这个循环,但这很有趣。我的外部
loop只需向后跳转 55 个字节,并且该函数除了打印或重新加载innerLoopCount之外不会触及内存(尽管最好从 sqrt(N) 设置它。或者也许更新只需在每次打印换行时重新计算即可。)
标签: loops assembly x86 masm code-size