This is a bizarre situation I'm in. I've tried writing this code to find prime numbers by trial division, in 8086 Assembly. It doesn't work, but even stranger is that when I was trying to debug it, I noticed that making the code any longer would cause the CPU to crash. Even adding a NOP
! I'm at a loss for why that is.
The code:
isPrime:
;input: AX = the number you wish to test (u16)
;output:
; carry clear = number is prime
; carry set = number is not prime
push ax
push bx
push cx
push dx
mov cx,ax
inc cx
;if the "loops" will fallthru carry will be clear already
loop $+5
; clc
jmp wasPrime ;if AX == 0 return CARRY CLEAR
loop $+5
; clc
jmp wasPrime ;else if AX == 1 return CARRY CLEAR
loop $+5
; clc
jmp wasPrime ;else if AX == 2 return CARRY CLEAR
;else
mov bx,3
mov cx,ax
loop_isPrime:
mov ax,cx
cmp ax,bx ;if we got so far that they're equal, it was prime
je wasPrime ;equal implies no carry
div bx ;remainder is in dx, quotient in ax. bx unchanged
test dx,dx
jz notPrime ;if divides w/o remainder, it wasn't prime(we won't get to equality this way)
inc bx ;next bx
jmp loop_isPrime
notPrime:
nop ;somehow adding anything here (even a nop) makes the program softlock!
stc ;not prime - set carry
wasPrime:
pop dx
pop cx
pop bx
pop ax
ret