• {面试题9: 斐波那契数列}


    From 剑指Offer 何海涛 著

    #include <iostream>
    using namespace std;
    
    long long fibonacciRecursively(unsigned int n) {
        if(n <= 1) {
            return n;
        }
        return fibonacciRecursively(n-1) + fibonacciRecursively(n-2);
    }
    
    long long fibonacciIteratively(unsigned int n) {
        long long res = 0ll;
        long long one = 0ll;
        long long two = 1ll;
        if(n == 0) {
            return one;
        }
        if(n == 1) {
            return two;
        }
        for(unsigned int i=2; i<=n; i++) {
            res = one + two;
            one = two;
            two = res;
        }
        return res;
    }
    
    struct Matrix2By2 {
        Matrix2By2(long long m00 = 0ll, long long m01 = 0ll, long long m10  = 0ll, long long m11 = 0ll) : m_00(m00), m_01(m01), m_10(m10), m_11(m11) {
    
        }
        long long m_00 ;
        long long m_01 ;
        long long m_10 ;
        long long m_11 ;
    };
    
    Matrix2By2 MatrixMultiply(const Matrix2By2& matrix1, const Matrix2By2& matrix2) {
        return Matrix2By2(
            matrix1.m_00 * matrix2.m_00 + matrix1.m_01 * matrix2.m_10,
            matrix1.m_00 * matrix2.m_01 + matrix1.m_01 * matrix2.m_11,
            matrix1.m_10 * matrix2.m_00 + matrix1.m_11 * matrix2.m_10,
            matrix1.m_10 * matrix2.m_01 + matrix1.m_11 * matrix2.m_11
            );
    }
    
    Matrix2By2 MatrixPowerCore(unsigned int n) {
    Matrix2By2 matrix;
    if(n == 1) {
    return Matrix2By2(1, 1, 1, 0);
    }
    matrix = MatrixPowerCore(n/2);
    matrix = MatrixMultiply(matrix, matrix);
    if(n % 2 != 0) {
    matrix = MatrixMultiply(matrix, Matrix2By2(1, 1, 1, 0));
    }
    return matrix;
    } Matrix2By2 MatrixPower(unsigned
    int n) { if(n == 0) { return Matrix2By2(); } if(n == 1) { return Matrix2By2(1, 1, 1, 0); }return MatrixPowerCore(n-1); }

    测试集:

    void test(unsigned int n, long long expected) {
        std::cout << std::boolalpha << (fibonacciRecursively(n) == expected) << std::endl;
        std::cout << std::boolalpha << (fibonacciIteratively(n) == expected) << std::endl;
        std::cout << std::boolalpha << (MatrixPower(n-1).m_00 == expected) << std::endl;
    }
    
    int main(int argc, char* argv[]) {
        test(0, 0ll);
        test(1, 1ll);
        test(2, 1ll);
        test(3, 2ll);
        test(4, 3ll);
        test(5, 5ll);
        test(6, 8ll);
        test(7, 13ll);
        test(8, 21ll);
        test(9, 34ll);
        test(10, 55ll);
        test(40, 102334155ll);
    
        return 0;
    }
  • 相关阅读:
    做开发的童鞋应该都了解这几款软件
    给文件对比工具自定义快捷键的方法
    C/C++ 编程有哪些值得推荐的辅助工具
    如何用Beyond Compare修改对比文件颜色
    据说这些工具可以提高程序员的工作效率
    遇到Beyond Compare禁止编辑该怎么办
    BZOJ
    周三
    大总结
    周二上午
  • 原文地址:https://www.cnblogs.com/long3216/p/4442324.html
Copyright © 2020-2023  润新知