Created
February 12, 2017 05:46
-
-
Save aaronjwood/8e2094aae6a4713150ad553685af198b to your computer and use it in GitHub Desktop.
Fibonacci 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 ( | |
"flag" | |
"fmt" | |
) | |
// Time: O(2^n) | |
// Space: O(n) | |
func FibRecursive(n uint64) uint64 { | |
if n <= 1 { | |
return n | |
} | |
return FibRecursive(n-1) + FibRecursive(n-2) | |
} | |
// Time: O(n) | |
// Space: O(1) | |
func FibIterative(n uint64) uint64 { | |
var fib uint64 | |
var i uint64 | |
var x, y uint64 = 0, 1 | |
for i = 0; i < n; i++ { | |
x = y | |
y = fib | |
fib = x + y | |
} | |
return fib | |
} | |
func main() { | |
method := flag.String("method", "iterative", "Either recursive or iterative") | |
num := flag.Uint64("number", 10, "nth fibonacci number") | |
flag.Parse() | |
if *method == "recursive" { | |
fmt.Println(FibRecursive(*num)) | |
} else if *method == "iterative" { | |
fmt.Println(FibIterative(*num)) | |
} | |
} |
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 "testing" | |
func BenchmarkFibRecursive(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
FibRecursive(30) | |
} | |
} | |
func BenchmarkFibIterative(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
FibIterative(30) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment