【问题标题】:Is it possible to calculate isFibonacci() in constant time?是否可以在恒定时间内计算 isFibonacci() ?
【发布时间】:2019-07-23 12:04:29
【问题描述】:

可以创建一个快速的“给出第 n 个斐波那契数”函数,如 here 所述。有没有办法编写一个在 O(1) 中执行的 isFibonacci(int i) 函数?

我可以预先计算值。但是计算最后 O(n) 并且我不能为大数字做。

【问题讨论】:

    标签: algorithm fibonacci


    【解决方案1】:

    一个数是斐波那契当且仅当 (5*n2 + 4) 或 (5*n2 – 4) 之一或两者是完美正方形.

    bool isFibonacci(int n) 
    { 
        // n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both 
        // is a perferct square 
        return isPerfectSquare(5*n*n + 4) || 
               isPerfectSquare(5*n*n - 4); 
    } 
    

    【讨论】:

    • (如何)isPerfectSquare 可以在恒定时间内实现?
    • @harold return round(sqrt(n))^2 == n;
    • @harold 或类似return isInteger(sqrt(n))
    • @DIBits 但这不是恒定的时间。它是sqrt(n)
    猜你喜欢
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多