Hi folks! :)

I'm here with a problem of Assembly 8086 (x86) (NASM). I´m trying calculate the sum of all numbers, which are odd, lowers than X (X = number defined by user)

Already solved the problem in C # and C + +, but i need the Assembly Code.

In C#:

``````int num = 0;
int res = 0;
int all = 0;
int soma = 0;

while (all < num)
{
all++;
res = all % 2;
if (res == 1)
{
soma += all;
}
else
{
continue;
}
}
Console.WriteLine(soma);``````

In C++:

``````int num = 0;
int all = 0;
int res = 0;
int soma = 0;

puts("Introduza o valor: ");
scanf_s("%d", &num);

while (all < num)
{
all++;
res = all % 2;
if (res ==1)
{
soma += all;
}
else
{
continue;
}
}
printf("Soma valores impares: %d",soma);``````

In Assembly:

``````%include "arq2010.asm"

LEA CX, [MSG1]	;Show MSG1
CALL WriteLine

LEA CX, [input]	;Read Input

;Most create the condition here!

.DATA
MSG1 DB "Input: ", 0
MSG2 DB "Output: ", 0``````

Appreciate help. Thanks! :)

Good news: you can make this much simpler !
I found a mathematical way to find it:

The sum of ALL numbers until n is given by: n*(n+1)/2
Since we want only odd numbers, we can modify it like this:

1 2 3 4 5 ...
0 1 2 3 4 ...
+______________
1 3 5 7 9 ...

So the formula is then: n*(n+1)/2 + (n-1)*n/2 = n²!
We're almost there, but when we give a n, it will give us all the numbers smaller than 2N.
We can use bitshift right, which halve the number AND round it down.
So the code is, assuming the input is in ax:

``````;assume the unsigned integer limit X is already in ax:
shr ax,1
mul ax
; done !``````

Thus this will calculate te sum of odd numbers strictly lower than X, so:
X = 15;
bitshift right: 00001111 --> 00000111 = 7;
square: 49 = 1 + 3 + 5 + 7 + 9 + 11 + 13;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.