learn go memoization

简介: package main // 参考文章: // https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/06.
package main

// 参考文章:
//     https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/06.12.md

import (
    "fmt"
    "time"
)

const LIM = 41

var fibs [LIM]uint64

func main() {
    var result uint64 = 0
    start := time.Now()
    for i := 0; i < LIM; i++ {
        result = fibonacci(i)
        fmt.Printf("fibonacci(%d) is: %d\n", i, result)
    }

    end := time.Now()
    delta := end.Sub(start)
    fmt.Printf("longCalculation took this amount of time:%s\n", delta)
}

func fibonacci(n int) (res uint64) {
    // memoization: check if fibonacci(n) is already known in array
    if fibs[n] != 0 {
        res = fibs[n]
        return
    }
    if n <= 1 {
        res = 1
    } else {
        res = fibonacci(n - 1) + fibonacci(n - 2)
    }

    fibs[n] = res
    return
}

 

目录
相关文章
|
4月前
|
Go
Go to Learn Go之命令行参数
Go to Learn Go之命令行参数
40 8
|
4月前
|
Serverless Go
Go to Learn Go之时间日期
Go to Learn Go之时间日期
50 8
|
4月前
|
Go
Go to Learn Go之Gob
Go to Learn Go之Gob
29 8
|
4月前
|
Go
Go to Learn Go之文件操作
Go to Learn Go之文件操作
33 8
|
4月前
|
Go
Go to Learn Go之反射
Go to Learn Go之反射
51 8
|
4月前
|
存储 安全 Go
Go to Learn Go之并发
Go to Learn Go之并发
35 8
|
4月前
|
存储 Go
Go to Learn Go之类型转换
Go to Learn Go之类型转换
48 7
|
4月前
|
Go
Go to Learn Go之错误处理
Go to Learn Go之错误处理
54 7
|
4月前
|
存储 Go
Go to Learn Go之接口
Go to Learn Go之接口
38 7
|
4月前
|
Go
Go to Learn Go之作用域
Go to Learn Go之作用域
30 5