Factors of an integer: Difference between revisions

Content added Content deleted
No edit summary
m (factors get saved at reserved RAM space instead of stack now)
Line 4,691: Line 4,691:
{{works with|nasm}}
{{works with|nasm}}
<lang asm>
<lang asm>
section .bss
factorArr resd 250 ;big buffer against seg fault
section .text
section .text
global _main
global _main
_main:
_main:
mov ebp, esp;program puts all factors on the local stack surrounded by 0xffffffff (-1)
mov ebp, esp; for correct debugging
mov eax, 12345 ;number of which we want to know the factors
mov eax, 0x7ffffffe ;number of which we want to know the factors, max num this program works with
mov ebx, eax ;save eax
mov ebx, eax ;save eax
mov ecx, 1 ;n, factor we test for
mov ecx, 1 ;n, factor we test for
mov [factorArr], dword 0
push -1; boundary
looping:
looping:
mov eax, ebx ;restore eax
mov eax, ebx ;restore eax
xor edx, edx ;clear edx
xor edx, edx ;clear edx
div ecx ;divide eax by ecx (our number by our current factor)
div ecx
cmp edx, 0 ;edx stores remainder, if it is 0 we have a factor
cmp edx, 0 ;test if our number % n == 0
jne next
jne next
push ecx ; we store the found factor on the stack
mov edx, [factorArr] ;if yes, we increment the size of the array and append n
inc edx
mov [factorArr+edx*4], ecx ;appending n
mov [factorArr], edx ;storing the new size
next:
next:
mov eax, ecx
mov eax, ecx
cmp eax, ebx ;compare the factor we test for with the actual number, if the factor is greater we jump to end
cmp eax, ebx ;is n bigger then our number ?
jg end
jg end ;if yes we end
inc ecx ;add 1 to the factor
inc ecx
jmp looping ;do it again
jmp looping
end:
end:
push -1 ;another -1 to mark the boundary on the other side
mov ecx, factorArr ;pass arr address by ecx
xor eax, eax ;clear eax
mov eax, ebp ;eax now contains highest address of the stack -> maybe call output with that
mov esp, ebp
mov esp, ebp ;garbage collecting
ret
ret
</lang>
</lang>