Comment convertir un int en bigint dans golang?
Je suis en train de mettre en œuvre rapide double de fibonacci de l'algorithme tel que décrit ici:
//Fast doubling Fibonacci algorithm
package main
import "fmt"
// (Public) Returns F(n).
func fibonacci(n int) int {
if n < 0 {
panic("Negative arguments not implemented")
}
fst, _ := fib(n)
return fst
}
//(Private) Returns the tuple (F(n), F(n+1)).
func fib(n int) (int, int) {
if n == 0 {
return 0, 1
}
a, b := fib(n / 2)
c := a * (b*2 - a)
d := a*a + b*b
if n%2 == 0 {
return c, d
} else {
return d, c + d
}
}
func main() {
fmt.Println(fibonacci(13))
fmt.Println(fibonacci(14))
}
Cela fonctionne très bien pour des petits nombres; toutefois, lorsque le nombre d'entrée sont de plus en plus, le programme renvoie un résultat erroné. J'ai donc essayé d'utiliser bigInt
de math/big
package:
//Fast doubling Fibonacci algorithm
package main
import (
"fmt"
"math/big"
)
// (Public) Returns F(n).
func fibonacci(n int) big.Int {
if n < 0 {
panic("Negative arguments not implemented")
}
fst, _ := fib(n)
return fst
}
//(Private) Returns the tuple (F(n), F(n+1)).
func fib(n int) (big.Int, big.Int) {
if n == 0 {
return big.Int(0), big.Int(1)
}
a, b := fib(n / 2)
c := a * (b*2 - a)
d := a*a + b*b
if n%2 == 0 {
return c, d
} else {
return d, c + d
}
}
func main() {
fmt.Println(fibonacci(123))
fmt.Println(fibonacci(124))
}
Cependant, d'aller construire se plaint que
cannot convert 0 (type int) to type big.Int
La façon d'atténuer ce problème?
- Essayez de gros.Int64(int nombre)
Vous devez vous connecter pour publier un commentaire.
Utilisation
big.NewInt()
au lieu debig.Int()
.big.Int()
est juste la conversion de type.Vous devez vérifier la documentation de
big
le paquetVous devriez surtout utiliser les méthodes de la forme
func (z *T) Binary(x, y *T) *T //z = x op y
Pour multiplier 2 arguments, vous devez fournir variable résultat, après appel
Mul
méthode. Ainsi, par exemple, pour obtenir le résultat de la 2*2 vous avez besoin de:big.NewInt(0).Mul(big.NewInt(2), big.NewInt(2))
Vous pouvez essayer d'exemple de travail sur la Aller de l'aire de jeux
Aussi, vous pouvez créer l'extension des fonctions comme:
Afin de rendre le code plus lisible:
L'essayer sur le Aller de l'aire de jeux
cannot use big.NewInt(0) (type *big.Int) as type big.Int in return argument
big.NewInt
retourne le pointeur de*big.Int
c := Mul(a, Sub(Mul(b, big.NewInt(2)), a))
ressemble LISP : )