gpt4 book ai didi

go - 获取 bigInt 数 golang 的总和

转载 作者:IT王子 更新时间:2023-10-29 02:11:17 26 4
gpt4 key购买 nike

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.

如果有人能帮我解决这个问题,我将不胜感激。

 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)))

}

最佳答案

修复了

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)))

}

看来您的问题可能与您调用其方法的 Big Int 对象将成为分配值的对象的方式有关,而不一定是参数之一。

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

关于go - 获取 bigInt 数 golang 的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46395819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com