25: 1000-digit fibonacci number

This commit is contained in:
VicRen
2020-10-24 22:04:23 +08:00
parent 86ae6bb4a7
commit 117fc7ab5f
2 changed files with 86 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
package main
import (
"fmt"
"math/big"
)
func main() {
n := 11
for {
fb := fibonacci(n)
fmt.Println("index =", n, "len =", len(fb.String()))
if numberDigits(fb) >= 1000 {
break
}
n++
}
fmt.Println("n is", n)
}
func fibonacci(index int) *big.Int {
if index < 3 {
ret := (&big.Int{}).SetUint64(1)
return ret
}
fn := &big.Int{}
fn1 := (&big.Int{}).SetInt64(1)
fn2 := (&big.Int{}).SetInt64(1)
for i := 3; i <= index; i++ {
fn.Set(fn.Add(fn1, fn2))
fn2.Set(fn1)
fn1.Set(fn)
}
return fn
}
func numberDigits(num *big.Int) int {
return len(num.String())
}

View File

@@ -0,0 +1,46 @@
package main
import (
"math/big"
"reflect"
"testing"
)
func Test_fibonacci(t *testing.T) {
type args struct {
index int
}
tt := []struct {
name string
args args
want *big.Int
}{
{
"1",
args{1},
(&big.Int{}).SetBits([]big.Word{1}),
},
{
"10",
args{10},
(&big.Int{}).SetBits([]big.Word{big.Word(55)}),
},
{
"12",
args{12},
(&big.Int{}).SetBits([]big.Word{big.Word(144)}),
},
{
"13",
args{13},
(&big.Int{}).SetBits([]big.Word{big.Word(233)}),
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if got := fibonacci(tc.args.index); !reflect.DeepEqual(got, tc.want) {
t.Errorf("fibonacci() = %v, want %v", got, tc.want)
}
})
}
}