Writing an Assembly Program to add from 1 to 100

1.4k views Asked by At

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:

IAS instructions I think will be sufficient to complete this task

I just cant seem to get this done. I dont even know where to begin, no real loops or if statements

1

There are 1 answers

5
Antonin GAVREL On

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-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

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/ hardcode n(n+1)/2 in your register. (equal to 5050)