Presentation is loading. Please wait.

Presentation is loading. Please wait.

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; }

Similar presentations


Presentation on theme: "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; }"— Presentation transcript:

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 jL1 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 fib: 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 jalfibfirst recursive call move$s0, $v0 addi$a0, $a0, -1 jalfibsecond 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.align2.globlmain main: li$v0, 4 la$a0, PR syscall li$v0, 5 syscall move$a0, $v0 jalfib move$a0, $v0 li$v0, 1 syscall li$v0, 4 la$a0, LF syscall li$v0,10 syscall

7 Main program.data.align4 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 1990-2000 by James R. Larus (larus@cs.wisc.edu). 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) run Enter a positive integer 8 21 (spim) exit


Download ppt "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; }"

Similar presentations


Ads by Google