Problem 6 on Project Euler with x86 Assembly


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

The problem:

——

The sum of the squares of the first ten natural numbers is,

12 + 22 + … + 102 = 385
The square of the sum of the first ten natural numbers is,

(1 + 2 + … + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

——

My Solution:

.text 
.globl main

main:
  /*-enter stack frame-*/
  pushl %ebp
  movl %esp, %ebp

  /*find square of sums*/
  movl $0, %eax
  movl $1, %ebx
  addNumbers:
    cmpl $100, %ebx
    jg doneAdding
    addl %ebx, %eax
    addl $1, %ebx
    jmp addNumbers
  doneAdding:
  movl %eax, %ebx
  imul %ebx, %eax

  /*find sum of squares*/
  movl $0, %ebx
  movl $1, %ecx
  squareNumbers:
    cmpl $100, %ecx
    jg doneSquaring
    movl %ecx, %edx
    movl %ecx, %edi
    imul %edx, %edi
    addl %edi, %ebx
    addl $1, %ecx
    jmp squareNumbers
  doneSquaring:

  subl %ebx, %eax
  pushl %eax
  pushl $string2
  call printf

  /*-leave stack frame-*/
  movl %ebp, %esp
  popl %ebp  

  movl $0, %eax
  ret
.data
string2: .string "result=%dn"

Leave a Reply

Your email address will not be published. Required fields are marked *