Finding the closest fibonacci numbers

前端 未结 11 2342

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:08

    I posted a complete Proof-Of-Concept implementation of this on https://ideone.com/H6SAd

    • it is blazingly fast
    • it uses an adhoc binary search
    • Edit after reading the other responses, I have a feeling that mathematical ideas outlined there (PengOne) will lead to a quicker lookup (basically: a calculation of the inverted formula plus a floor()/ceil() call?)

    .

    #include 
    #include 
    
    const double pheta = 0.5*(std::sqrt(5)+1);
    
    double fib(unsigned int n)
    {
        return (std::pow(pheta, n) - std::pow(1 - pheta, n)) / std::sqrt(5);
    }
    
    unsigned int fibo_lowerbound(double N, unsigned min=0, unsigned max=1000)
    {
        unsigned newpivot = (min+max)/2;
        if (min==newpivot)
            return newpivot;
    
        if (fib(newpivot) <= N)
            return fibo_lowerbound(N, newpivot, max);
        else
            return fibo_lowerbound(N, min, newpivot);
    }
    
    std::pair fibo_range(unsigned int n)
    {
        unsigned int lbound = fibo_lowerbound(n);
        return std::make_pair(fib(lbound), fib(lbound+1));
    }
    
    void display(unsigned int n)
    {
        std::pair range = fibo_range(n);
        std::cout << "Fibonacci range wrapping " << n << " is "
                  << "[" << (unsigned long long) range.first << ", " << (unsigned long long) range.second << "]"
                  << std::endl;
    }
    
    int main()
    {
        display(1044);
        display(8999913);
        display(7);
        display(67);
    }
    

    The output is:

    Fibonacci range wrapping 1044 is [987, 1597]
    Fibonacci range wrapping 8999913 is [5702887, 9227465]
    Fibonacci range wrapping 7 is [5, 8]
    Fibonacci range wrapping 67 is [55, 89]
    

提交回复
热议问题