TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
fibonacci.cpp
Go to the documentation of this file.
1
12
13
#include <cstdint>
14
#include <cassert>
15
#include <iostream>
16
21
namespace
math
{
26
namespace
fibonacci
{
32
uint64_t
fibonacci
(uint64_t n) {
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
}
42
}
// namespace fibonacci
43
}
// namespace math
44
49
static
void
test
() {
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
}
59
64
int
main
() {
65
test
();
// run self-test implementations
66
return
0;
67
}
test
static void test()
Self-test implementation.
Definition
fibonacci.cpp:49
main
int main()
Main function.
Definition
fibonacci.cpp:64
math::fibonacci::fibonacci
uint64_t fibonacci(uint64_t n)
Function to compute the n-th Fibonacci number.
Definition
fibonacci.cpp:32
fibonacci
Functions for Fibonacci sequence.
math
for assert
math
fibonacci.cpp
Generated by
1.13.2