Problem 7 on Project Euler with x86 Assembly


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

The problem:


By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

My solution:

.text 
.globl main

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

  movl $3, %edi
  movl $1, %esi
  mainLoop:
    pushl %edi
    call isPrime
    pop %ebx
    cmp $1, %eax
    jne notPrime
    addl $1, %esi
    cmp $10001, %esi
                je found
    notPrime:
    addl $2, %edi
    jmp mainLoop
  found:

  pushl %edi
  pushl $string2
  call printf

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

  movl $0, %eax
  ret

isPrime:
  pushl %ebx
  pushl %edi
  movl 12(%esp), %edi
  cmp $1, %edi
  je returnYes
  cmp $2, %edi
  je returnYes
  movl $0, %edx
  movl %edi, %eax
  movl $2, %ebx
  idiv %ebx
  cmp $0, %edx
  je returnNo
  movl $3, %ecx
  divisionLoop:
    cmp %ecx, %edi
    jle returnYes
    movl $0, %edx
    movl %edi, %eax
    idiv %ecx
    cmp $0, %edx
    je returnNo
    addl $2, %ecx
    jmp divisionLoop
  returnNo:
  movl $0, %eax
  jmp end
  returnYes:
  movl $1, %eax
  end:
  popl %edi
  popl %ebx
  ret

.data
string2: .string "result=%dn"

Leave a Reply

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