Finding the closest fibonacci numbers

前端 未结 11 2151

I am trying to solve a bigger problem, and I think that an important part of the program is spent on inefficient computations.

I need to compute for a given number N, th

11条回答
  •  一向
    一向 (楼主)
    2021-02-02 14:10

    Since you consider only 64 bit integers, there are at most about 100 Fibonacci numbers to consider. You can precompute them using their definition Fn = Fn-1 + Fn-2.

    Then precompute another table that maps the number of leading zero bits to an index in the table of Fibonacci numbers, to the first number with that many leading zero bits.

    Now to find the interval use the number of leading zero bits of your number (this can be computed quickly as many processors have a special instruction for it) to find a starting point using the second table, and linearly search through the first table for the interval. Since there are at most two Fibonacci numbers between adjacent powers of two this takes at most 2 steps.

    This has the advantage that it only uses integer arithmetic, which is exact and tends to be faster than floating point computations.

提交回复
热议问题