0

I'm trying to print prime numbers between 2 - 100000. But there's something wrong with my code. When It detects a non prime number It should go to the next one, yet it still prints it out, so instead of 2, 3, 5, 7.. I'm getting 2 3 4 5 6 7...

%include "io64.inc"

section .text
global CMAIN
CMAIN:

    PRINT_DEC 1,2
    NEWLINE

    reset_ebx:
    mov ebx,2
    loop2:
    xor edx,edx
    mov eax,[num]
    div ebx
    inc ebx
    cmp ebx,[num+1]
    je end
    cmp edx,0
    je loop2
    cmp edx,0
    jne prime


    prime:
    PRINT_DEC 8,[num]
    NEWLINE


    end:
    mov eax,[num]
    inc eax  ; 3 - 10000
    mov [num],eax
    cmp eax,10001 
    jne reset_ebx

    xor rax, rax
    ret

    section .data
    num dq 3
    max_ebx dq 0
    const dq 2
  • related: [Checking if a number is prime in NASM Win64 Assembly](https://codereview.stackexchange.com/a/204965) explains how to write a trial-division loop that sucks as little as possible. It's not clear exactly what you're saying happens when you run this; describe your [mcve] more clearly. – Peter Cordes May 15 '20 at 15:47
  • I mean that when it detects a non prime number, it should increment and check the next one. It goes( 2 / check if prime / If yes then print ) 3... etc... and It prints every number there is instead of only prime ones –  May 15 '20 at 15:51
  • Ok, that's clearer, good edit. `cmp ebx,[num+1]` offsets the address by one byte, not the value. So presumably that's always going to be false. A single instruction is limited to what the HW can do, and addressing modes only calculate addresses, not run the loaded value through an ALU operation before using it with the instruction mnemonic on that line. – Peter Cordes May 15 '20 at 16:11

1 Answers1

2

You are jumping to the label prime when edx is not zero however because the label immediately follows this code when it is zero the computer will simply fallthrough and start executing the code in that label.

Labels in Assembly are not analogous to functions or code blocks found in higher level languages, if you do not trigger a jump (either explicitly such as with a Jxx instruction, or implicitly such as with a call) the computer will simply carry on executing in a linear fashion.

If you switch jne prime to je end your code should be fixed.

0x777C
  • 993
  • 7
  • 21