TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
fibonacci.cpp File Reference

n-th Fibonacci number. More...

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

Go to the source code of this file.

Namespaces

namespace  math
 for assert
 
namespace  fibonacci
 Functions for Fibonacci sequence.
 

Functions

uint64_t math::fibonacci::fibonacci (uint64_t n)
 Function to compute the n-th Fibonacci number.
 
static void test ()
 Self-test implementation.
 
int main ()
 Main function.
 

Detailed Description

n-th Fibonacci number.

Naive recursive implementation to calculate the n-th Fibonacci number.

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

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

Definition in file fibonacci.cpp.

Function Documentation

◆ fibonacci()

uint64_t math::fibonacci::fibonacci ( uint64_t n)

Function to compute the n-th Fibonacci number.

Parameters
nthe index of the Fibonacci number
Returns
n-th element of the Fibonacci's sequence

Definition at line 32 of file fibonacci.cpp.

32 {
33 // If the input is 0 or 1 just return the same (Base Case)
34 // This will set the first 2 values of the sequence
35 if (n <= 1) {
36 return n;
37 }
38
39 // Add the preceding 2 values of the sequence to get next
40 return fibonacci(n - 1) + fibonacci(n - 2);
41}
Functions for Fibonacci sequence.

◆ main()

int main ( void )

Main function.

Returns
0 on exit

Definition at line 64 of file fibonacci.cpp.

64 {
65 test(); // run self-test implementations
66 return 0;
67}
static void test()
Self-test implementation.
Definition fibonacci.cpp:49

◆ test()

static void test ( )
static

Self-test implementation.

Returns
void

Definition at line 49 of file fibonacci.cpp.

49 {
50 assert(math::fibonacci::fibonacci(0) == 0);
51 assert(math::fibonacci::fibonacci(1) == 1);
52 assert(math::fibonacci::fibonacci(2) == 1);
53 assert(math::fibonacci::fibonacci(3) == 2);
54 assert(math::fibonacci::fibonacci(4) == 3);
55 assert(math::fibonacci::fibonacci(15) == 610);
56 assert(math::fibonacci::fibonacci(20) == 6765);
57 std::cout << "All tests have passed successfully!\n";
58}