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
13#include <cstdint>
14#include <cassert>
15#include <iostream>
16
21namespace math {
26namespace fibonacci {
32uint64_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
49static 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
64int main() {
65 test(); // run self-test implementations
66 return 0;
67}
static void test()
Self-test implementation.
Definition fibonacci.cpp:49
int main()
Main function.
Definition fibonacci.cpp:64
Functions for Fibonacci sequence.
for assert