dongshushi5579 2017-02-19 15:14
浏览 101
已采纳

Golang怪异big.Int行为,位数很少

I am trying to calculate the GCD of two numbers via the Euclidean method, and noticed weird behavior. Although I am passing the value of the number to the function, the numbers are modified by the function for numbers with low number of bits (usually less than 64). Could anyone clarify if this is a mistake on my behalf or is it expected behavior? You can check the code in the playground here: Golang playground example

I thought the expected behavior is that no values should be changed by passing them to my functions. Thanks for any help, I couldn't find any other occurrences like this in the last day of searching.

  • 写回答

1条回答 默认 最新

  • dongquming3255 2017-02-19 16:41
    关注

    big.Int is a struct containing nat, which is defined as type nat []Word so, while you are indeed copying the big.Int, the slice inside it is effectively a shallow copy (underlying storage for slice is same)

    For why the bigger bit widths don't exhibit the problem, not sure.

    Possibly it requires a reallocation somewhere and that creates a new []Word thereby leaving the original in tact.

    This is also probably why the stdlib generally returns *big.Int, since a value isn't really copyable

    here's a version on play that properly copies the big.Int values. The key difference being:

    a := new(big.Int).Set(x)
    b := new(big.Int).Set(y)
    

    (and using pointers in general as values aren't particularly useful)

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化