Find the product of an array of big.ints


(yewebi) #1

Hello, I have an array of big.int and need to find the product of all the elements (i.e compute 3x5x7 in the following simple example). It seems big.int pointers are a bit hard to handle. Can someone help? Thanks!

package main

import (
	"fmt"
	"math/big"
)

func main() {
			testarray := make([]*big.Int, 3)
			entry1 := new(big.Int)
			entry2 := new(big.Int)
			entry3 := new(big.Int)
			number1 := "3"
			number2 := "5"
			number3 := "7"
			entry1.SetString(number1, 10)
			entry2.SetString(number2, 10)
			entry3.SetString(number3, 10)
			testarray[0] = entry1
			testarray[1] = entry2
			testarray[2] = entry3
			fmt.Println(testarray)
}

( Kvaz1r) #2

It really would be much simple if you read the documentation.

package main

import (
	"fmt"
	"math/big"
)

func main() {
	testarray := []*big.Int{big.NewInt(3), big.NewInt(5), big.NewInt(7)}
	fmt.Println(testarray)
	var R *big.Int = big.NewInt(1)

	for _, v := range testarray {
		R.Mul(R, v)
	}
	fmt.Println(R)
}

https://play.golang.org/p/HU35Xk1PuqR