math.big 用于大整数计算
作者:互联网
https://www.cnblogs.com/welhzh/p/8981096.html
1, math/big
package main
import (
"fmt"
"math/big"
"time"
)
const LIM = 10000 //求第10000位的费布拉切数
var fibs [LIM]*big.Int //使用数组保存计算出来的费布拉切数的指针
func main() {
result := big.NewInt(0)
start := time.Now()
for i := 0; i < LIM; i++ {
result = fibonacci(i)
if i == LIM-1 {
fmt.Printf("fibonacci(%d) is: %d\n", i, result)
}
}
fmt.Println(result)
fmt.Printf("%T\n", result)
end := time.Now()
delta := end.Sub(start)
fmt.Printf("longCalculation took this amount of time: %s\n", delta)
}
func fibonacci(n int) (res *big.Int) {
if n <= 1 {
res = big.NewInt(1)
} else {
temp := new(big.Int)
res = temp.Add(fibs[n-1], fibs[n-2])
}
fibs[n] = res
return
}
2, math/big
package main
import (
"fmt"
"math/big"
)
func genFibLst(n int) (a []string) {
n1 := big.NewInt(1)
n2 := big.NewInt(1)
fmt.Printf("n1=%d,type(n1)=%T n2=%d,type(n2)=%T\n",n1,n1,n2,n2)
fmt.Printf("n1=%s, n2=%s, n1.string=%s\n",n1,n2,n1.String())
fmt.Printf("n1=%#v, n1=%v \n",n1,n1)
fmt.Printf("n1=%#v, n1=%v %v \n",n1,n1,*n1)
fmt.Printf("n2=%#v, n2=%v %v\n",n1,n1,*n2)
for n > 0 {
a = append(a, n1.String())
tmp := n1.Add(n1, n2)
fmt.Printf("----------n1=%s, n2=%s, a=%v,tmp=%s \n",n1,n2,a,tmp)
n1 = n2
n2 = tmp
n --
}
return a
}
func main() {
lst := genFibLst(10)
for index, val := range lst {
fmt.Println(">>>",index + 1, val)
}
}
标签:big,fmt,整数,Printf,n1,n2,math 来源: https://www.cnblogs.com/heris/p/16188379.html