Write a program in MASM (32 bit) that calculates the sum of all odd numbers in the Fibonacci sequence between 0 and 1,000,000.
***Please Complete in MASM 32 bit!!***
Program:
Sample output:
Code to copy:
;fib.asm
global _main
extern _printf
SECTION .data ; data section
msg1: db 'All odd numbers in the Fibonacci sequence between 0 and 1,000,000:',10,0 ; the string to print, 10=cr
msg2: db 'Sum of all these odd numbers : ',10,0 ; the string to print, 10=cr
fmt: db "%d", 10, 0 ; The printf format, "\n",'0'
f1: dd 0
f2: dd 1
sum: dd 0
oddsum: dd 1
section .text
_main:
push msg1 ; print the label msg1
call _printf
add esp, 4 ; pop stack 4 bytes
push ebp ; set up stack frame
mov ebp,esp
mov eax, [f2]
push eax ; the 1st odd number (1) of the sequence
push dword fmt ; push format string
call _printf ; print the 1st odd number (1) of the sequence
add esp, 8 ; pop stack 2 push times 4 bytes
_printnext:
; take prevoius two terms into eax and ebx
mov eax, [f1] ; put a from store into register
mov ebx,[f2]
add eax,ebx ; generate next term
mov [sum],eax ; save the next term into sum
mov ecx,1000000
cmp ecx,eax ; compare whether this term is less than 1000000
jl _exit ; if the term exceeds 1000000, exit the loop
; otherwise, check the term is odd or even
mov ebx,eax
mov ecx ,2
div ecx ; divide the term by 2. eax= quetient , edx=remainder
mov eax,1
cmp edx,eax ; check whether the remainder is 1 or 0
jnz _next ; if the term is even, go to next iteration
mov eax,[oddsum]
add eax,ebx ; if the term is odd, add it to oddsum
mov [oddsum],eax ; update oddsum
push ebx ; pass term to printf
push dword fmt ; pass format string to printf
call _printf ; Call C function to print the term
add esp, 8 ; pop stack 2 push times 4 bytes
_next:
mov ebx,[f2] ; update the prevoius terms
mov [f1],ebx
mov ebx,[sum]
mov [f2],ebx
jmp _printnext ; go to _printnext
_exit:
push msg2 ; print the label msg2
call _printf
add esp, 4 ; pop stack 1 push times 4 bytes
mov eax,[oddsum] ; mov the oddsum into eax
push eax ; pass oddsum to push
push dword fmt ; pass the format string to printf
call _printf ; Call C function to print the term
add esp,8 ; pop stack 2 push times 4 bytes
mov esp, ebp ; takedown stack frame
pop ebp
mov eax,0 ; normal, no error, return value
ret
Get Answers For Free
Most questions answered within 1 hours.