Download presentation
Presentation is loading. Please wait.
Published byMichael Brecher Modified over 9 years ago
1
Fibonacci with Loop int fib1(int i) { int f1 = 1; int f2 = 1; int f3;
while (i >= 3) { f3 = f1+f2; f1 = f2; f2 = f3; i--; } return f2;
2
Fibonacci with loop fib: li $t0, 1 li $v0, 1 li $t1, 3
L1: blt $a0, $t1, fibExit add $t2, $t0, $v0 move $t0, $v0 move $v0, $t2 addi $a0, $a0, -1 j L1 fibExit: jr $ra
3
Fibonacci with Recursion
int fib(int i) { if (i < 3) return 1; int j = fib(i-1); int k = fib(i-2); return j+k; }
4
Fibonacci with recursion
addi $sp, $sp, -16 sw $s0, 12($sp) sw $s1, 8($sp) sw $a0, 4($sp) sw $ra, 0($sp) li $s0, 0 li $s1, 1 li $t1, 3 L1: blt $a0, $t1, fibExit addi $a0, $a0, -1 jal fib first recursive call move $s0, $v0 jal fib second recursive call move $s1, $v0
5
Fibonacci with recursion
fibExit: add $v0, $s0,$s1 lw $s0, 12($sp) lw $s1, 8($sp) lw $a0, 4($sp) lw $ra, 0($sp) addi $sp, $sp, 16 jr $ra
6
Main program .text .align 2 .globl main main: li $v0, 4 la $a0, PR
syscall li $v0, 5 move $a0, $v0 jal fib li $v0, 1 la $a0, LF li $v0,10
7
Main program .data .align 4 PR: .asciiz "Enter a positive integer "
LF: .asciiz "\n"
8
Execute spim gendreaus-computer:fall10 tom$ spim
SPIM Version 6.3a of January 14, 2001 Copyright by James R. Larus All Rights Reserved. See the file README for a full copyright notice. Loaded: ./trap.handler (spim) read "Fib1.s" (spim) run Enter a positive integer 8 21 (spim) read "Fib2.s" (spim) exit
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.