dongshandun4363 2017-09-24 23:32
浏览 130
已采纳

获取bigInt号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)))

}
  • 写回答

1条回答 默认 最新

  • duanbinian2243 2017-09-24 23:58
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址