Last active
September 22, 2024 14:05
-
-
Save pedrobertao/a31466b3287f165f22d05f0fb2b066f2 to your computer and use it in GitHub Desktop.
Recursive and Iterative Fibonnaci Sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func fibRecursive(position uint) uint { | |
if position <= 2 { | |
return 1 | |
} | |
return fibRecursive(position-1) + fibRecursive(position-2) | |
} | |
func fibIterative(position uint) uint { | |
slc := make([]uint, position) | |
slc[0] = 1 | |
slc[1] = 1 | |
if position <= 2 { | |
return 1 | |
} | |
var result, i uint | |
for i = 2; i < position; i++ { | |
result = slc[i-1] + slc[i-2] | |
slc[i] = result | |
} | |
return result | |
} | |
func main() { | |
pos := uint(8) | |
fmt.Printf("%d\n", (fibRecursive(pos))) | |
// Output = 21 | |
fmt.Printf("%d\n", (fibIterative(pos))) | |
// Output = 21 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment