I'm learning Go and I started using the math/big
package to deal with arbitrary-length integer.
I wrote this program that computes the n-th Fibonacci number : (removed the import
s) :
func main() {
imax, _ := strconv.Atoi(os.Args[1])
var a, b, c big.Int
a.SetUint64(0)
b.SetUint64(1)
for i := 0; i < imax; i++ {
c.Set(&b)
b.Add(&b, &a)
a.Set(&c)
}
fmt.Println(a.String())
}
Here's the code for the C program :
int main(int argc, char** argv)
{
int imax = atoi(argv[1]);
mpz_t a, b, c;
mpz_inits(a, b, c, NULL);
mpz_set_ui(a, 0);
mpz_set_ui(b, 1);
int i = 0;
for (i = 0; i < imax; i++) {
mpz_swap(a, b);
mpz_add(b, a, b);
}
char* astr = NULL;
astr = mpz_get_str(NULL, 10, a);
printf("%s
", astr);
return EXIT_SUCCESS;
}
The Go program computes the term 100,000 in 0.1 second (average), while the C equivalent, using the GMP lib, runs in 0.04 second only. That's two times slower.
Is there a way to get the same performance in my Go program ?