fibonacci.cpp 1.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/**
 * @file
 * @brief Generate fibonacci sequence
 *
 * Calculate the the value on Fibonacci's sequence given an
 * integer as input.
 * \f[\text{fib}(n) = \text{fib}(n-1) + \text{fib}(n-2)\f]
 *
 * @see fibonacci_large.cpp, fibonacci_fast.cpp, string_fibonacci.cpp
 */
V
vonzo 已提交
11
#include <cassert>
12
#include <iostream>
V
vonzo 已提交
13

14 15 16
/**
 * Recursively compute sequences
 */
17
unsigned int fibonacci(unsigned int n) {
V
vonzo 已提交
18 19 20 21 22 23
    /* If the input is 0 or 1 just return the same
       This will set the first 2 values of the sequence */
    if (n <= 1)
        return n;

    /* Add the last 2 values of the sequence to get next */
24
    return fibonacci(n - 1) + fibonacci(n - 2);
V
vonzo 已提交
25 26
}

27 28 29
/**
 * Function for testing the fibonacci() function with a few
 * test cases and assert statement.
30 31 32 33
 * @returns `void`
*/
static void test() {
    unsigned int test_case_1 = fibonacci(0);
34 35 36
    assert(test_case_1 == 0);
    std::cout << "Passed Test 1!" << std::endl;

37
    unsigned int test_case_2 = fibonacci(1);
38 39 40
    assert(test_case_2 == 1);
    std::cout << "Passed Test 2!" << std::endl;

41
    unsigned int test_case_3 = fibonacci(2);
42 43 44
    assert(test_case_3 == 1);
    std::cout << "Passed Test 3!" << std::endl;

45
    unsigned int test_case_4 = fibonacci(3);
46 47 48
    assert(test_case_4 == 2);
    std::cout << "Passed Test 4!" << std::endl;

49
    unsigned int test_case_5 = fibonacci(4);
50 51 52
    assert(test_case_5 == 3);
    std::cout << "Passed Test 5!" << std::endl;

53
    unsigned int test_case_6 = fibonacci(15);
54 55 56 57
    assert(test_case_6 == 610);
    std::cout << "Passed Test 6!" << std::endl << std::endl;
}

58
/// Main function
V
vonzo 已提交
59
int main() {
60
    test();
V
vonzo 已提交
61 62 63 64 65
    int n;
    std::cin >> n;
    assert(n >= 0);
    std::cout << "F(" << n << ")= " << fibonacci(n) << std::endl;
}