我有一个问题,我正在为期末考试而学习。这是个问题:
编写程序以计算用户输入的negative-only_and_divisible_by_4整数的总和,直到用户输入正值100为止。
以下是我的代码,它正在运行。我想知道是否有更有效的方法来检查数字是否可以被4整除。
.data
prompt BYTE "No Positive Numbers!",0
done BYTE "Finished..",0
notdivisible BYTE "This number is not divisble!",0
.code
start:
mov ebx,0
readin:
call ReadInt
cmp eax,100
je finish
cmp eax,0
jg positive
mov ecx,eax
neg ecx
checkifdivisible:
sub ecx,4
cmp ecx,0
jl notdiv
jg checkifdivisible
je divisible
divisible:
add ebx,eax
LOOP readin
notdiv:
mov edx,OFFSET notdivisible
call WriteString
call Crlf
jmp readin
positive:
mov edx,OFFSET prompt
call WriteString
call Crlf
jmp readin
finish:
call Crlf
mov edx,OFFSET done
call WriteString
xchg ebx,eax
call Crlf
call WriteInt
exit
end start
感谢大家提前帮助我制作更高效的代码!我觉得这个答案太长了。
答案 0 :(得分:2)
如果n
,则n AND 3 == 0
可以被4整除。 C检查:
#include <stdio.h>
#include <stdint.h>
static void
is_div4(int32_t n)
{
printf("%5d => 0x%08x, %d, %.2f\n",
n, n, ((uint32_t) n & 3) == 0, (double) n / 4.0);
}
int
main(int argc, char **argv)
{
is_div4(-100);
is_div4(-4);
is_div4(-102);
is_div4(-338);
is_div4(-108);
return 0;
}
输出:
-100 => 0xffffff9c, 1, -25.00
-4 => 0xfffffffc, 1, -1.00
-102 => 0xffffff9a, 0, -25.50
-338 => 0xfffffeae, 0, -84.50
-108 => 0xffffff94, 1, -27.00
简单实施:
mov eax, NUMBER
and eax, 0x3
cmp eax, 0
jne NotDividableBy4
; dividable by 4
NotDividableBy4:
;