Last active
December 14, 2021 21:23
-
-
Save jtprogru/d9479c1f132575c3dcf9a82b1da41f8a to your computer and use it in GitHub Desktop.
recursion may be faster
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" | |
"time" | |
) | |
func main() { | |
startTime := time.Now() | |
fmt.Println("Run -> Fib") | |
res := wrapCachedFib(1000) | |
fmt.Println(res) | |
endTime := time.Now() | |
fmt.Printf("Duration: %dmicros\n", endTime.UnixMicro()-startTime.UnixMicro()) | |
fmt.Println("------------------------------------------------------------") | |
sTime := time.Now() | |
fmt.Println("Run -> Fib") | |
r := classicFib(50) | |
fmt.Println(r) | |
eTime := time.Now() | |
fmt.Printf("Duration: %dmicros\n", eTime.UnixMicro()-sTime.UnixMicro()) | |
} | |
func classicFib(n uint64) uint64 { | |
if n == 0 { | |
return 0 | |
} | |
if n == 1 { | |
return 1 | |
} | |
a := classicFib(n - 2) | |
b := classicFib(n - 1) | |
return a + b | |
} | |
func cachedFib(n uint64, cache []uint64) uint64 { | |
if n == 0 { | |
return 0 | |
} | |
if n == 1 { | |
return 1 | |
} | |
if cache[n] == 0 { | |
a := cachedFib(n-2, cache) | |
b := cachedFib(n-1, cache) | |
cache[n] = a + b | |
} | |
return cache[n] | |
} | |
func wrapCachedFib(n uint64) uint64 { | |
cache := make([]uint64, n+1) | |
return cachedFib(n, cache) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result output:
WOW!