Skip to content

Instantly share code, notes, and snippets.

@pedrobertao
Last active September 5, 2024 08:34
Show Gist options
  • Save pedrobertao/a31466b3287f165f22d05f0fb2b066f2 to your computer and use it in GitHub Desktop.
Save pedrobertao/a31466b3287f165f22d05f0fb2b066f2 to your computer and use it in GitHub Desktop.
Recursive and Iterative Fibonnaci Sequence
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