Golang斐波那契数的计算显示为关机Golang

2023-09-11 05:45:23 作者:心疼无法治愈

目前,我有以下的codeS为我斐波纳契计算。我试图计算大数,但现在看来,一旦它到达100,计算关闭。对于FIB(100),我的code返回3736710778780434371,但是当我看到其他来源,它告诉我正确的计算应该是354224848179261915075.有没有在我的code的一个问题还是有与我计算机硬件或其他什么东西?

 包主
进口FMT

FUNC FIB(N UINT)UINT {


  无功表[] UINT
  表=令([] UINT,N + 1)
  表[0] = 0
  表[1] = 1


  对于i:= UINT(2); I< = N; I + = 1 {

     表[I] =表[I-1] +表[I-2]


  }

  返回表[N]

}

FUNC的main(){
   fmt.Println(FIB(100))
}
 

解决方案

你打一个整数溢出!你可以只计算使用 UINT 达的尺寸 UINT ;一旦你超越它的界限,它会(默默)回卷圆了。

在你的情况下,它看起来就像一个 UINT 64位长。 (其大小取决于你正在运行的平台上。)这意味着你将能够存储值高达2 64 -1。如果再增加一个,它会翻转到0,并不会返回一个错误。

庙算在前,多算胜 斐波那契技术面10月展望

如果你转换你得到的答案和正确答案,为十六进制数,那么你会看到这种情况。你结束与

  33DB76A7C594BFC3
 

而正确的答案是

  1333DB76A7C594BFC3
 

请注意,您的答案是正确的,只要它去...它只是还远远不够。你只得到了较低的64位答案;你错过了其他13 * 2 64 。

要纠正它,你需要,而不是使用任意大小的整从结构大, UINT

I currently have the following codes for my fibonacci calculations. I'm trying to calculate large numbers, but it appears once it gets to 100, the calculations are off. For fib(100), my code returns 3736710778780434371, but when I look at other sources, it tells me the correct calculation should be 354224848179261915075. Is there a problem in my code or does it have to do with my computer hardware or something else?

package main
import "fmt"

func fib(N uint) uint{


  var table []uint
  table = make([]uint, N+1)
  table[0] = 0
  table[1] = 1


  for i := uint(2); i <= N; i += 1 {

     table[i] = table[i-1] + table[i-2]


  }

  return table[N]

}

func main() {
   fmt.Println(fib(100))
}

解决方案

You're hitting an integer overflow! You can only calculate using a uint up to the size of a uint; once you go beyond its bounds, it will (silently) wrap back round again.

In your case, it looks as though a uint is 64 bits long. (Its size depends on the platform you're running on.) That means that you will be able to store values up to 264-1. If you then add one more, it'll wrap back to 0, and won't return an error.

If you convert the answer you're getting, and the right answer, into hex, then you'll see that this is the case. You're ending up with

  33DB76A7C594BFC3

whereas the right answer is

1333DB76A7C594BFC3

Note that your answer is correct as far as it goes... it just doesn't go far enough. You've only got the lower 64 bits of the answer; you're missing the other 13*264.

To correct it, you'll need to use an arbitrary size integer from Package big, instead of a uint.