Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
fibonacci.cpp File Reference

Generate fibonacci sequence. More...

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

Functions

uint64_t fibonacci (uint64_t 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()

uint64_t fibonacci ( uint64_t n)

Recursively compute sequences

Parameters
ninput
Returns
n-th element of the Fbinacci's sequence
19 {
20 /* If the input is 0 or 1 just return the same
21 This will set the first 2 values of the sequence */
22 if (n <= 1) {
23 return n;
24 }
25
26 /* Add the last 2 values of the sequence to get next */
27 return fibonacci(n - 1) + fibonacci(n - 2);
28}
uint64_t fibonacci(uint64_t n)
Definition fibonacci.cpp:19
Here is the call graph for this function:

◆ main()

int main ( void )

Main function.

62 {
63 test();
64 int n = 0;
65 std::cin >> n;
66 assert(n >= 0);
67 std::cout << "F(" << n << ")= " << fibonacci(n) << std::endl;
68}
T endl(T... args)
static void test()
Definition fibonacci.cpp:35
Here is the call graph for this function:

◆ test()

static void test ( )
static

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

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