问题
So im trying to add 1+2+3... and so on...without using brute force. Y=∑_1^100▒X_i, the numbers Xi are stored in consecutive memory locations starting at location 100. I am using the IAS instruction set:
I just cant seem to get this done. I dont even know where to begin, no real loops or if statements
回答1:
You have 4 different possible approaches, that I will write in x86 since my knowledge of IAS is very limited, but you can apply the same logic
1/ Brute force
xor eax, eax
mov ecx, 100
.myloop:
add eax, ecx
dec ecx
jnz .myloop
2/ From brute force logic you can load value at memory address (which seems to be what you want to do? I add from 100 to 1.
xor eax, eax
mov ecx, 100
.myloop:
lea edx, [100+ecx*4] ; assuming integer array
add eax, edx
dec ecx
jnz .myloop
3/ A more efficient way, and assuming the numbers follow each other and starting from 1, you can use the famous formula res = n(n+1) / 2
. If you think about a dice, the sum from 1 to 6 is 21, which is exactly 6 * 7 / 2. To avoid the INT_MAX overflow I would suggest to test if the bit of n is set, if it is set divide n+1 by 2, else divide n by 2
lea edx, [100+100*4] ; load value 100 in register edx
test edx, 1
jnz .planb
mov eax, edx
shr eax
inc edx
imul eax, edx
leave
ret
.planb:
mov eax, edx
inc eax
shr eax
imjl eax, edx
leave
ret
4/ hardcode n(n+1)/2 in your register. (equal to 5050)
来源:https://stackoverflow.com/questions/61198765/writing-an-assembly-program-to-add-from-1-to-100