Here's a C version just for you.
#include <stdio.h>
int main()
{
unsigned long i,j=2,k=0,x=0;
for(i=1;i<=1002001;i+=j){x+=i;if(k==4){k=0;j+=2;}k++;}
printf("sum is %u\n",x);
return 0;
} Since posting I have reviewed some other solutions. Everyone else completed this with a different algorithm. To me, this one was less complicated though. The above assembler can also be dropped inline in a C program.
int main()
{
unsigned long x;
x=myasm();
printf("sum is %u\n",x);
return 0;
}
unsigned long myasm()
{
asm("
mov ecx, 1
xor ebx, ebx
mov eax, ecx
inner:
add ebx, 2
mov edx, 4
outer:
add ecx, ebx
cmp ecx, 1002001
ja getout
add eax, ecx
dec edx
jz inner
jmp outer
getout:
");
} compiled with:
gcc -o spiral spiral.c -masm=intel