Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
fibonacci.cpp File Reference

Generate fibonacci sequence. More...

#include <cassert>
#include <iostream>
Include dependency graph for fibonacci.cpp:

Functions

unsigned int fibonacci (unsigned int n)
 
static void test ()
 
int main ()
 Main function.
 

Detailed Description

Generate fibonacci sequence.

Calculate the the value on Fibonacci's sequence given an integer as input.

\[\text{fib}(n) = \text{fib}(n-1) + \text{fib}(n-2)\]

See also
fibonacci_large.cpp, fibonacci_fast.cpp, string_fibonacci.cpp

Function Documentation

◆ fibonacci()

unsigned int fibonacci ( unsigned int  n)

Recursively compute sequences

17  {
18  /* If the input is 0 or 1 just return the same
19  This will set the first 2 values of the sequence */
20  if (n <= 1)
21  return n;
22 
23  /* Add the last 2 values of the sequence to get next */
24  return fibonacci(n - 1) + fibonacci(n - 2);
25 }

◆ test()

static void test ( )
static

Function for testing the fibonacci() function with a few test cases and assert statement.

Returns
void
32  {
33  unsigned int test_case_1 = fibonacci(0);
34  assert(test_case_1 == 0);
35  std::cout << "Passed Test 1!" << std::endl;
36 
37  unsigned int test_case_2 = fibonacci(1);
38  assert(test_case_2 == 1);
39  std::cout << "Passed Test 2!" << std::endl;
40 
41  unsigned int test_case_3 = fibonacci(2);
42  assert(test_case_3 == 1);
43  std::cout << "Passed Test 3!" << std::endl;
44 
45  unsigned int test_case_4 = fibonacci(3);
46  assert(test_case_4 == 2);
47  std::cout << "Passed Test 4!" << std::endl;
48 
49  unsigned int test_case_5 = fibonacci(4);
50  assert(test_case_5 == 3);
51  std::cout << "Passed Test 5!" << std::endl;
52 
53  unsigned int test_case_6 = fibonacci(15);
54  assert(test_case_6 == 610);
55  std::cout << "Passed Test 6!" << std::endl << std::endl;
56 }
Here is the call graph for this function:
fibonacci
unsigned int fibonacci(unsigned int n)
Definition: fibonacci.cpp:17
std::cout
std::endl
T endl(T... args)