Search code examples
gobigintsum-of-digits

get sum of bigInt number golang


Hi i am new to the golang programming language. I can get the bigint value from the factoral function but it is not working with the add function.

i have had the add function accepting bigint but when i try to add a .Mod and .Div methods it returns 0 fro some reason. the if else statement in the add function is an old statement i was using when i had int values coming from the factoral function.

it worked perfectly when it was as int value. When i attempted to alter the if else statement to accept bigint values i couldn't get it to work at all.

I have tried the .Mod and .Div methods and they are printing out the correct values. But when i try to .Add them together it always returns 0. even if the values are "22", "2". I've put the if else statement back to the original int values for now.

if anyone can help me out with this one i would be very greatful.

 package main

import (
    "fmt"
    "math/big"
)

func factoral(n uint64) (r *big.Int) {

    one, bn := big.NewInt(1), new(big.Int).SetUint64(n)

    r = big.NewInt(1)
    if bn.Cmp(one) <= 0 {
        return
    }
    for i := big.NewInt(2); i.Cmp(bn) <= 0; i.Add(i, one) {
        r.Mul(r, i)
    }
    return
}

func add(number *big.Int) *big.Int {
    //this the statement that works with normal int values
    if number/10 < 10 {
        return sum + number/10
    } else {
        return sum + add(number/10)
    }

}
func main() {
    fmt.Println(add(factoral(100)))

}

Solution

  • Fixed it

    package main
    
    import (
        "fmt"
        "math/big"
    )
    
    func factoral(n uint64) (r *big.Int) {
    
        one, bn := big.NewInt(1), new(big.Int).SetUint64(n)
    
        r = big.NewInt(1)
        if bn.Cmp(one) <= 0 {
            return
        }
        for i := big.NewInt(2); i.Cmp(bn) <= 0; i.Add(i, one) {
            r.Mul(r, i)
        }
        return
    }
    
    func add(number *big.Int) *big.Int {
        ten := big.NewInt(10)
        sum := big.NewInt(0)
        mod := big.NewInt(0)
        for ten.Cmp(number)<0 {
          sum.Add(sum, mod.Mod(number,ten))
          number.Div(number,ten)
        }
        sum.Add(sum,number)
      return sum
    }
    func main() {
        fmt.Println(add(factoral(100)))
    
    }
    

    Seems your issue was likely with the way the Big Int object whose method you invoke is going to be the one the value is assigned to, and not necessarily one of the arguments.

    See: https://golang.org/pkg/math/big/#Int.Div