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)
InformationsquelleAutor Nick | 2015-11-12