编写汇编程序以将其添加到1到100 [英] Writing an Assembly Program to add from 1 to 100
问题描述
因此,我试图在不使用蛮力的情况下添加1 + 2 + 3 ...,依此类推. Y = ∑_1 ^100▒X_i,数字Xi存储在从位置100开始的连续内存位置中.我使用的是IAS指令集:
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:
我似乎无法做到这一点. 我什至不知道从哪里开始,没有真正的循环或if语句
I just cant seem to get this done. I dont even know where to begin, no real loops or if statements
推荐答案
您有4种可能的方法,由于我对IAS的了解非常有限,我将用x86编写这些方法,但是您可以应用相同的逻辑
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/蛮力
xor eax, eax
mov ecx, 100
.myloop:
add eax, ecx
dec ecx
jnz .myloop
2/从暴力逻辑中,您可以在内存地址中加载值(这似乎是您想要的?我将100加到1.
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-4] ; assuming integer array
add eax, [edx]
dec ecx
jnz .myloop
3/一种更有效的方法,并假设数字彼此相邻并从1开始,则可以使用著名的公式res = n(n+1) / 2
.如果考虑骰子,则1到6的和为21,正好是6 * 7/2.为避免INT_MAX溢出,我建议测试n的位是否已设置(如果已设置)除n + 1除以2,否则n除以2
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
mov edx, [100+99*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
imul eax, edx
leave
ret
4/寄存器中的硬编码n(n + 1)/2. (等于5050)
4/ hardcode n(n+1)/2 in your register. (equal to 5050)
这篇关于编写汇编程序以将其添加到1到100的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!